分享一个asp.net 导出假Excel代码。优点,不用借助于任何插件比如(NPOI),复制代码,修改grid.DataSource直接导出。
先看导出后的效果图
1 System.Web.UI.WebControls.DataGrid grid = new DataGrid(); 2 grid.CellSpacing = 6; 3 grid.CellPadding = 6; 4 grid.EnableViewState = false; 5 grid.DataSource = tableCars; 6 grid.DataBind(); 7 foreach (DataGridColumn clos in grid.Columns) 8 { 9 clos.HeaderStyle.Width = 200; 10 clos.ItemStyle.Width = 200; 11 } 12 System.IO.StringWriter tw = new System.IO.StringWriter(); 13 HtmlTextWriter hw = new HtmlTextWriter(tw); 14 grid.RenderControl(hw); 15 string fileName = System.Web.HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8); 16 HttpContext.Current.Response.Charset = "utf-8"; 17 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; 18 HttpContext.Current.Response.ContentType = "application/ms-excel"; 19 HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); 20 HttpContext.Current.Response.Write(tw.ToString()); 21 HttpContext.Current.Response.End();
时间: 2024-10-29 19:11:14