protected void Button2_Click(object sender, EventArgs e) { if (this.GridView1.Rows.Count == 0) { Response.Write("<script>alert('沒有查找到數(shù)據(jù),無法導出!')"); } else { this.GridView1.AllowPaging = false; // 將有分頁的GridView中的數(shù)據(jù)全部導出到Excel gvBond(); export("application/ms-excel", "工作人員.xls"); // 換成 export("application/ms-word", "工作人員.doc"); 那么導出的就是Word格式的了. this.GridView1.AllowPaging = true; gvBond(); } } public void export(string FileType, string FileName) { string style = @"<style>.text{mso-number-format:/@}</script>";//導入到excel時,保存表里數(shù)字列中前面存在的 0 . Response.Clear(); Response.Charset = "GB2312"; Response.ContentEncoding = Encoding.UTF7; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); Response.ContentType = FileType; this.EnableViewState = false; this.GridView1.AllowPaging = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); this.GridView1.RenderControl(htw); Response.Write(style); Response.Write(sw.ToString()); //Response.Write(dt.ToString()); Response.End(); }
public override void VerifyRenderingInServerForm(Control control) { //在后臺中重載VerifyRenderingInServerForm()方法,否則報錯為“類型"GridView"的控件"GridView1"必須放在具有 runat=server 的窗體標記內(nèi)“ } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[3].Attributes.Add("class", "text");//在數(shù)字列前存在的 0 的列中加入 class 樣式 以便保存 0 } }
注:如果GricView中有分頁的話,導出到Excel時就會報錯.可通過修改頁文件可以修正這個問題:EnableEventValidation = "false".
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
請選中你要保存的內(nèi)容,粘貼到此文本框
|