Method 1: write the code directly on the page
/// <Summary>
/// Export data
/// </Summary>
/// <Param name = "FileType"> FileType = "application/vnd.xls"; </param>
/// <Param name = "FileName"> </param>
Private void Export (string FileType, string FileName)
{
Response. Charset = "GB2312 ";
Response. ContentEncoding = System. Text. Encoding. UTF8; // pay attention to Encoding
Response. appendHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. urlEncode (FileName, Encoding. UTF8 ). toString (). trim () + ". xls ");
Response. ContentType = FileType;
This. EnableViewState = false;
StringWriter tw = new StringWriter ();
HtmlTextWriter hw = new HtmlTextWriter (tw );
GridGatewayDetails. RenderControl (hw );
Response. Write (tw. ToString ());
Response. End ();
}
Method 2: Improve the above Code to a public method:
/// <Summary>
/// Export grid data to Excel
/// </Summary>
/// <Param name = "ctrl"> grid name (such as GridView1) </param>
/// <Param name = "filetype"> file type to be exported (Excel: Application/MS-Excel) </param>
/// <Param name = "FILENAME"> name of the file to be saved </param>
Public static void gridviewtoexcel (control Ctrl, string filetype, string filename)
{
Httpcontext. Current. response. charset = "gb2312 ";
Httpcontext. Current. response. contentencoding = encoding. utf8; // pay attention to Encoding
Httpcontext. Current. response. appendheader ("content-disposition ",
"Attachment; filename =" + httputility. urlencode (filename, encoding. utf8). tostring ());
HttpContext. Current. Response. ContentType = FileType; // image/JPEG; text/HTML; image/GIF; vnd. ms-excel/msword
Ctrl. Page. EnableViewState = false;
StringWriter tw = new StringWriter ();
HtmlTextWriter hw = new HtmlTextWriter (tw );
Ctrl. RenderControl (hw );
HttpContext. Current. Response. Write (tw. ToString ());
HttpContext. Current. Response. End ();
}
Iii. Notes:
During export, if a field is a long number (such as ID card number 511922198507151512) or a number starting with 0 (such as 0809111212. If not processed, the exported Excel files will be treated as 5.11922E + 17 and 809111212 respectively, which is inconsistent with the actual effect we want to achieve. So we need to process it, that is, to specify the format of the cell data. The common format is as follows:
1) Text: vnd. ms-excel.numberformat :@
2) Date: vnd. ms-excel.numberformat: yyyy/mm/dd
3) number: vnd. ms-excel.numberformat: #,## 0.00
4) Currency: vnd. ms-excel.numberformat: ¥ #, #0.00
5) percentage: vnd. ms-excel.numberformat: # 0.00%
The usage is as follows:
// Set the format of the first cell
E. Item. Cells [0]. Attributes. Add ("style", "vnd. ms-excel.numberformat :@");
// Set the format of the fourth cell
E. Item. Cells [3]. Attributes. Add ("style", "vnd. ms-excel.numberformat: ¥ #, ###. 00 ");
This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/suchgoingdown/archive/2009/03/10/3977013.aspx