Asp.net exports an Excel file and asp.net exports an excel file
Referring to other ways of writing on the Internet, the RenderControl function of the control is used to obtain the HTML generated by the control and then output it to the client as an Excel file.
The difference is that I added the Response. Flush () method myself, so the download box is displayed when the data is generated, instead of waiting for a while on the same page.
Click the export Excel button. The download box is displayed.
Note: Response. Flush () is used to output the buffer information to the page.
/// <Summary> /// export the DataTable content to excel and return to the client // </summary> /// <param name = "header"> header line </param> /// <param name = "fileName"> file name </param> public void DataTable2Excel (TableCell [] header, string fileName) {// IO is used to export and return the excel file var strWriter = new StringWriter (); var htmlWriter = new HtmlTextWriter (strWriter); // sets the encoding and attachment format Response. contentType = "application/ms-excel"; Response. contentEncoding = Encodin G. GetEncoding ("gb2312"); Response. Charset = "gb2312"; if (! String. isNullOrEmpty (fileName) {fileName = HttpUtility. urlEncode (fileName, Encoding. UTF8); // handle Chinese name garbled Response. appendHeader ("Content-Disposition", ("attachment; filename =" + (fileName. toLower (). endsWith (". xls ")? FileName: fileName + ". xls ");} Response. flush (); var gvExport = new GridView (); // redefine a pageless GridView var dt = new able (); // The data gvExport to be exported. dataSource = dt. defaultView; gvExport. allowPaging = false; gvExport. rowDataBound + = dgExport_RowDataBound; // optimizes the display of exported data, such as ID card and 12-1. dataBind (); if (header! = Null & header. length> 0) // process the header {gvExport. headerRow. cells. clear (); gvExport. headerRow. cells. addRange (header);} gvExport. renderControl (htmlWriter); // return the client Response. write (strWriter); Response. end ();}
/// <Summary> /// used to optimize the display of exported data /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> protected void dgExport_RowDataBound (object sender, gridViewRowEventArgs e) {if (e. row. rowType! = DataControlRowType. dataRow) return; foreach (var cell in e. row. cells. cast <TableCell> (). where (cell => Regex. isMatch (cell. text. trim (), @ "^ \ d {12,} $") | Regex. isMatch (cell. text. trim (), @ "^ \ d + [-] \ d + $") {cell. attributes. add ("style", "vnd. ms-excel.numberformat :@");}}
Summary:
1. Errors will always be reported during method calling:Server cannot set content type after HTTP headers have been sent.
Cause: the Response. Flush () method is called before the Response. AppendHeader method is called.
2. Error:Must be placed in the form tag with runat = server.
Solution: public override void VerifyRenderingInServerForm (Control control) {}// NO content needs to be added