Today, I got the control to export the Excel file, so the format was incorrect. For example, the name of some dates such as 20091222 was displayed as a scientific note.
So I searched the blog Park. A lot of articles are copied to copy the materials.
Basically there is a line of shiny code: Text: vnd. ms-excel.numberformat :@
There is a deeper article that will tell you that this thing should be written in <td style = "vnd. ms-excel.numberformat: @"> xxx </td>
The two branch methods are generated here:
1. Write <td style = "vnd. ms-excel.numberformat: @"> <% # Eval ("XXX") %> </td>
2. There is no way to directly write <td, so if the Table is directly generated by the GridView and so on, the background circular output method will be used:
Take a piece of text here:
// Format the columns to be formatted
// E. Item. Cells [0]. Attributes. Add ("style", "vnd. ms-excel.numberformat :@");
Bytes --------------------------------------------------------------------------------------
In fact, after exporting an Excel file, if you use NotePad to open it, you can find that it is almost an html file.
That is, html, and style can also be used. Since external styles cannot be referenced, simply write internal styles.
So I produced such a short piece of code:
Code
HttpContext. Current. Response. Clear ();
HttpContext. Current. Response. ContentEncoding = System. Text. Encoding. GetEncoding ("gb2312 ");
HttpContext. Current. Response. Write ("<meta http-equiv = Content-Type content = text/html; charset = gb2312> ");
HttpContext. Current. Response. AppendHeader ("content-disposition", "attachment?filename=export.xls ");
HttpContext. Current. Response. ContentType = "application/vnd. ms-excel ";
StringBuilder sb = new StringBuilder ();
Sb. append ("HtmlTextWriter htw = new HtmlTextWriter (sw );
Foreach (Control ct in ctList)
{
Ct. RenderControl (htw );
}
Sb. Append (sw. ToString ());
Sw. Close ();
HttpContext. Current. Response. Write (sb. ToString ());
HttpContext. Current. Response. End ();
Now, you can add the <style> </style> style before the output to control the Excel output format.