1月22日 导出Excel注意的问题
代码
2 protected void BtnDaochuExcl_Click(object sender, EventArgs e)
3 {
4 gvList.Columns[7].Visible = false;
5 //清除客户端当前显示
6 Response.Clear();
7 Response.Buffer = true;
8 Response.Charset = "GB2312";
9 //显示标头
10 Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("文件名", System.Text.Encoding.UTF8) + ".xls");//这样的话,可以设置文件名为中文,且文件名不会乱码。其实就是将汉字转换成UTF8
11 Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
12 Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
13 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
14 System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
15 gvList.RenderControl(htmlWrite);
16 Response.Write(stringWrite.ToString());
17 Response.End();
18 }
19 public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
20 {
21
22 }
23 #endregion
主要比较新的就是采用中文名字,记下来以后用~!
最后那个VerifyRenderingInServerForm(System.Web.UI.Control control)方法的作用我也找来了一篇文章,贴过来原文地址http://www.cnblogs.com/wmj/archive/2009/09/20/1570698.html
事实上,问题到此,并没有完全解决,还是会把整个页面上的控件都导出来。
我们先休息一下,我们会发现,当我们点击导出Button的时候,响应给我们的输出流是一个excel页,而非默认的aspx页(context.Response.ContentType = "application/excel";),这样新的问题又来了,页面上的控件在rendering的时候,都会调用VerifyRenderingInServerForm方法,来检查当前控件是否在ServerForm标记内(调试过,确实如此)。很明显,我们输出的文档类型是"application/excel",而非默认的"text/html"类型,控件当然不在Form之中,因此也会抛出异常(控件不在Form中的异常),结果,系统又调用默认的输出流,把整个页都导出来了。
这个问题,很好解决,重写VerifyRenderingInServerForm方法,什么事也不干(也就是阻止系统调用默认的VerifyRenderingInServerForm方法)
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
//base.VerifyRenderingInServerForm(control);
}
总结
问题的关键是导出excel的时候,输出文件已经不是合法的aspx文件,我们唯一的办法,就是阻止系统掉用控件的检查方法,防止抛出异常,导致系统调用默认的输出方法,从而导致整个页面的控件都被导出。
25日发现导出的长字符串自动转换为科学计数法啦,上网查了查,解决方案如下,看代码:
代码
{
//1) 文本:vnd.ms-excel.numberformat:@
//2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
//3) 数字:vnd.ms-excel.numberformat:#,##0.00
//4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
//5) 百分比:vnd.ms-excel.numberformat: #0.00%
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); //你要转换的那一行的索引
}
}

浙公网安备 33010602011771号