. Net to export able to word, Excel, txt, htm method
Dt: DataTable
StrFile: fileName
StrExt: type
Private void GridExport (DataTable dt, string strFile, string strExt)
{
String strAppType = "";
Switch (strExt)
{
Case "xls ":
StrAppType = "application/ms-excel ";
Break;
Case "doc ":
StrAppType = "application/ms-word ";
Break;
Case "txt ":
StrAppType = "application/ms-txt ";
Break;
Case "html ":
Case "htm ":
StrAppType = "application/ms-html ";
Break;
Default: return;
}
GridView MyGridView = new GridView ();
MyGridView. DataSource = dt;
MyGridView. DataBind ();
HttpContext. Current. Response. Clear ();
HttpContext. Current. Response. Buffer = true;
HttpContext. Current. Response. AddHeader ("Content-Type", "text/html; charset = GB2312 ");
HttpContext. current. response. appendHeader ("Content-Disposition", string. format ("attachment; filename = {0 }. {1} ", HttpUtility. urlEncode (strFile, Encoding. getEncoding ("GB2312"), strExt ));
HttpContext. Current. Response. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
HttpContext. Current. Response. ContentType = strAppType;
// MyGridView. Page. EnableViewState = false;
// 2. Define an input stream
System. Globalization. CultureInfo myCItrad = new System. Globalization. CultureInfo ("ZH-CN", true );
System. IO. StringWriter oStringWriter = new System. IO. StringWriter (myCItrad );
System. Web. UI. HtmlTextWriter oHtmlTextWriter = new System. Web. UI. HtmlTextWriter (oStringWriter );
// 3. Bind the target data to the input stream output
MyGridView. RenderControl (oHtmlTextWriter );
HttpContext. Current. Response. Write (oStringWriter. ToString ());
HttpContext. Current. Response. End ();
}