将GridView中的数据导出到Excel代码与注意事项

时间:2022-02-11 19:51:23
  

//gv:需要导出数据的GridView,filename:导出excel文件名
public void ExportToExcel(GridView gv, string filename)
{
string style = @"<style> .text { mso-number-format:\@; } </style> "; Response.ClearContent();
HttpContext.Current.Response.Charset = "UTF8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;//注意编码
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.PageSize = Int16.MaxValue;
//导出之前一定要再次绑定数据源,不然导出无数据
gv.DataSource = getGridViewData();
gv.DataBind();
gv.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
} //必须加上这个函数,函数中没有任何内容只是重载一下,不然会报错:... type 'GridView' must be placed inside a form tag with runat=server.
public override void VerifyRenderingInServerForm(Control control)
{
} //可以在每行数据绑定的时候设置数据格式
//文本:vnd.ms-excel.numberformat:@
//日期:vnd.ms-excel.numberformat:yyyy/mm/dd
//数字:vnd.ms-excel.numberformat:#,##0.00
//百分比:vnd.ms-excel.numberformat: #0.00%
protected void IBDetailGridView_RowDataBound(object sender, GridViewRowEventArgs e) {
   if (e.Row.RowIndex > -1)
   {
     e.Row.Cells[7].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
     e.Row.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
  }
}