格式化GridView并导出Excel
1 /// <summary>
2 /// 导出成为Excel
3 /// </summary>
4 /// <param name="exportTargetGridView">目标GridView</param>
5 /// <param name="visibleNum">隐藏的列数</param>
6 /// <param name="content">说明内容</param>
7 public static void ExportExcel(GridView exportTargetGridView, int visibleNum, string content)
8 {
9 HttpContext.Current.Response.ClearContent();
10
11 HttpContext.Current.Response.Charset = "GB2312";
12
13 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
14
15 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
16
17 HttpContext.Current.Response.ContentType = "application/excel";
18
19 StringWriter sw = new StringWriter();
20
21 HtmlTextWriter htw = new HtmlTextWriter(sw);
22
23 for (int i = 0; i < visibleNum; i++)
24 {
25 exportTargetGridView.Columns[exportTargetGridView.Columns.Count - (i + 1)].Visible = false;
26 }
27
28 exportTargetGridView.RenderControl(htw);
29
30 sw.WriteLine(content + exportTargetGridView.Rows.Count.ToString());
31
32 HttpContext.Current.Response.Write(sw.ToString());
33
34 HttpContext.Current.Response.End();
35 }
2 /// 导出成为Excel
3 /// </summary>
4 /// <param name="exportTargetGridView">目标GridView</param>
5 /// <param name="visibleNum">隐藏的列数</param>
6 /// <param name="content">说明内容</param>
7 public static void ExportExcel(GridView exportTargetGridView, int visibleNum, string content)
8 {
9 HttpContext.Current.Response.ClearContent();
10
11 HttpContext.Current.Response.Charset = "GB2312";
12
13 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
14
15 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
16
17 HttpContext.Current.Response.ContentType = "application/excel";
18
19 StringWriter sw = new StringWriter();
20
21 HtmlTextWriter htw = new HtmlTextWriter(sw);
22
23 for (int i = 0; i < visibleNum; i++)
24 {
25 exportTargetGridView.Columns[exportTargetGridView.Columns.Count - (i + 1)].Visible = false;
26 }
27
28 exportTargetGridView.RenderControl(htw);
29
30 sw.WriteLine(content + exportTargetGridView.Rows.Count.ToString());
31
32 HttpContext.Current.Response.Write(sw.ToString());
33
34 HttpContext.Current.Response.End();
35 }
同时,还要重写
public override void VerifyRenderingInServerForm(Control control)
{
}
{
}
如果含有类似于身份证这样的数据,在导出成为Excel后将变成科学计数法的形式显示,所以可以通过以下方式进行转换,该段代码应写在RowDataBound事件中
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
{
e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
KidYang