GridView导出Excel问题

      前段时间听WebCast时写了篇观后感,呵呵《导出Excel--随心所欲的使用GridView听后记》 。主要是谈了一下GridView导出Excel,当时看能导出Excel后,也就没在深入下去。最近帮朋友做一套进销存软件,其中也设计到导出Excel的功能,发现问题远没有这么简单。
      现在就发现两个问题:
      1、 乱码问题
       这个“乱码”真是太躁人了,一开始以为是配置问题,在IIS里搞了半天设置成gb2312。哎,好了,可在来一次又出乱码了。总之是有时乱码,有时又没有,头都大了。最后在网上找到了一个解决办法:
       将原先的    
               Response.ContentEncoding = System.Text.Encoding.UTF8;
               Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
          改成
              Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
              还要注意的是这里的charset要和config的设置相同,否则也会有乱码

      2、 GridView的样式问题
       这就是一个视觉问题,我的GridView背景色是深灰色,以至于导出的Excel也是灰灰的,很是难看。所以俺就在导出前,动态 改了一下样式。

这是代码:

 1 public override void VerifyRenderingInServerForm(Control control)
 2    {
 3        // Confirms that an HtmlForm control is rendered for
 4    }

 5
 6    protected void ibExport_Click(object sender, ImageClickEventArgs e)
 7    {
 8        Response.Clear();
 9        Response.AddHeader("content-disposition""attachment;filename=FileName.xls");
10        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
11
12        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
13        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
14
15        gvMain.AllowPaging = false;
16        //BindData();
17        KuCun kcMain = new KuCun();
18       
19        gvMain.BackColor = System.Drawing.Color.White;
20        gvMain.ForeColor = System.Drawing.Color.Black;
21        gvMain.BorderWidth = 1;
22        gvMain.RowStyle.BackColor = System.Drawing.Color.White;
23        gvMain.RowStyle.ForeColor = System.Drawing.Color.Black;
24        gvMain.AlternatingRowStyle.BackColor = System.Drawing.Color.White;
25        gvMain.BorderStyle = BorderStyle.Solid;
26        gvMain.BorderWidth = 1;
27        gvMain.AlternatingRowStyle.ForeColor = System.Drawing.Color.Black;
28
29        kcMain.GridViewListOfAustria(gvMain, QueryString(), 0);
30
31        gvMain.RenderControl(htmlWrite);
32
33        Response.Write(stringWrite.ToString());
34        Response.End();
35
36
37        gvMain.AllowPaging = true;
38        //BindData();
39        kcMain.GridViewListOfAustria(gvMain, QueryString(), 0);
40    }

目前就发现了这两点问题,以后发现我会及时补充!

原文地址:https://www.cnblogs.com/xpengfee/p/822057.html