日期:2014-05-17 浏览次数:20669 次
public void GridviewToExcel(Control ctl, string FileName) { HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.ContentType = "application/ms-excel"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName); ctl.Page.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); ctl.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); }
//这地方有些问题,隐藏某些列(列索引从0开始)的时候,导出的excel会出现乱码 //GridView1.Columns[4].Visible = false;//隐藏选择列,不导出选择列 //GridView1.Columns[5].Visible = false;//隐藏选择列,不导出选择列 GridviewToExcel(GridView1, "jdccx.xls"); GridView1.AllowPaging = true; GridView1.AllowSorting = true; //GridView1.Columns[4].Visible = true;//恢复选择列为可见 //GridView1.Columns[5].Visible = true;//恢复选择列为可见 GridView1.DataBind();
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> private System.Data.DataTable GetData() { String[] testData = { "Yes", "No", "" }; System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser"); System.Data.DataRow dr; dataTable1.Columns.Add(new System.Data.DataColumn("Id", typeof(System.Int32))); dataTable1.Columns.Add(new System.Data.DataColumn("标题", typeof(System.String))); dataTable1.Columns.Add(new System.Data.DataColumn("State", typeof(System.String))); dataTable1.Columns.Add(new System.Data.DataColumn("负责人", typeof(System.String))); for (int i = 0; i < 8; i++) { dr = dataTable1.NewRow(); dr[0] = i; dr[1] = "标题标题标题标题标题标题标题标题标题标题【孟子E章】" + i.ToString(); dr[2] = testData[i % 3]; dr[3] = "标题标题标题标题标题标题标题标题标题标题【孟子E章】" + i.ToString(); dataTable1.Rows.Add(dr); } return dataTable1; } bool isExport = false; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { isExport = false; GridView1.DataSource = this.GetData(); GridView1.DataBind(); } } public void GridviewToExcel(Control ctl, string FileName) { HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.ContentType = "application/ms-excel"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName); ctl.Page.EnableViewState = false; System.IO.Stri