这个是老生常谈了,网上有很多博文介绍。这里自己也写下来方便以后查看。
先贴代码
public static void ExportGridView(GridView gv, string fileName)
{
string attachment = "attachment; filename=" + fileName + ".xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.Rows[i];
row.Cells[0].Attributes.Add("class", "textmode");
}
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
string style = @"<style> .textmode { mso-number-format:\#; } </style>";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
说明:
1,导出的是.xls的,暂时没找到导出.xlsx的。以后找到再记。
string attachment = "attachment; filename=" + fileName + ".xlsx";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
没有解决问题,导出的文件打不开。
2,fileName如果包含中文,在IE下导出后会是乱码。需要编码。
3,如果导出的某一行的数字显示成“1.222E+11”的形式,可以添加样式{ mso-number-format:\#; }。
遍历GridView的行
GridViewRow row = gv.Rows[i];
给每一行的单元格添加样式。
row.Cells[0].Attributes.Add("class", "textmode");
4,需要重写事件,否则会报错,说“GridView 需要放在runat=server的容器里”。
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}