Copy codeThe Code is as follows:
# Region DataTable export to Excel
/// <Summary>
/// DataTable export data to Excel
/// </Summary>
/// <Param name = "pData"> DataTable </param>
/// <Param name = "pFileName"> export file name </param>
/// <Param name = "pHeader"> export the title to | split </param>
Public static void DataTableExcel (System. Data. DataTable pData, string pFileName, string pHeader)
{
System. Web. UI. WebControls. DataGrid dgExport = null;
// Current Dialog
System. Web. HttpContext curContext = System. Web. HttpContext. Current;
// IO is used to export and return an excel file
System. IO. StringWriter strWriter = null;
System. Web. UI. HtmlTextWriter htmlWriter = null;
If (pData! = Null)
{
String UserAgent = curContext. Request. ServerVariables ["http_user_agent"]. ToLower ();
If (UserAgent. IndexOf ("firefox") =-1) // firefox
PFileName = HttpUtility. UrlEncode (pFileName, System. Text. Encoding. UTF8 );
CurContext. Response. AddHeader ("Content-Disposition", "attachment; filename =" + pFileName + ". xls ");
CurContext. Response. ContentType = "application/vnd. ms-excel ";
StrWriter = new System. IO. StringWriter ();
HtmlWriter = new System. Web. UI. HtmlTextWriter (strWriter );
// To solve the possible paging problem in dgData, You need to redefine a non-Paging DataGrid.
DgExport = new System. Web. UI. WebControls. DataGrid ();
DgExport. DataSource = pData. DefaultView;
DgExport. AllowPaging = false;
DgExport. ShowHeader = false; // remove the title
DgExport. DataBind ();
String [] arrHeader = pHeader. Split ('| ');
String strHeader = "<table border = \" 1 \ "style = \" background-color: Gray; font-weight: bold; \ "> <tr> ";
Foreach (string j in arrHeader)
{
StrHeader + = "<td>" + j. ToString () + "</td> ";
}
StrHeader + = "</tr> </table> ";
// Return to the Client
DgExport. RenderControl (htmlWriter );
String strMeta = "<meta http-equiv = \" content-type \ "content = \" application/ms-excel; charset = UTF-8 \ "/> ";
CurContext. Response. Write (strMeta + strHeader + strWriter. ToString ());
CurContext. Response. End ();
}
}
# Endregion