Some time ago, I wrote an article about WebCast, "Export Excel-use the GridView to listen to postscript as you like". I mainly talked about how to export the Excel in the GridView. After reading the Excel file, I didn't go into depth. Recently, I helped my friends develop a set of invoicing software, which also designed the Excel export function, and found that the problem is far from that simple.
Now we can find two problems:
1. garbled
This "garbled code" is really tricky. At first I thought it was a configuration problem and set it to gb2312 for half a day in IIS. Ah, okay, you can try again. In short, it is sometimes garbled, sometimes not, And the header is big. Finally, I found a solution on the Internet:
Response. ContentEncoding = System. Text. Encoding. UTF8;
Response. ContentType = "application/ms-excel"; // set the output file type to an excel file.
Change
Response. Write ("<meta http-equiv = Content-Type content = text/html; charset = gb2312> ");
It should also be noted that the charset here should be the same as the config settings, otherwise there will be garbled characters
2. style issues of the GridView
This is a visual problem. My GridView background color is so dark gray that the exported Excel is also gray and ugly. So I changed the style dynamically before exporting it.
This is the code:
1 public override void VerifyRenderingInServerForm (Control control)
2 {
3 // Confirms that an HtmlForm control is rendered
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}
I have found these two problems now. I will try again later!