/// <summary>
2./// 把DataTable內容導出excel並返回客戶端
3./// </summary>
4./// <param name="dgData">待導出的DataTable</param>
5./// 創 建 人:陳文凱
6./// 建立日期:2005年10月08日
7./// 修 改 人: ranbolwb 修改導出中文亂碼的問題
8./// 修改日期: 2012-05-29
9.public static void DataTable2Excel(System.Data.DataTable dtData)
10.{
11. System.Web.UI.WebControls.DataGrid dgExport = null;
12. // 當前對話
13. System.Web.HttpContext curContext = System.Web.HttpContext.Current;
14. // IO用於導出並返回excel文件
15. System.IO.StringWriter strWriter = null;
16. System.Web.UI.HtmlTextWriter htmlWriter = null;
17.
18. if (dtData != null)
19. {
20. // 設置編碼和附件格式
21. curContext.Response.ContentType = "application/vnd.ms-excel";
22. curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
23. curContext.Response.Charset = "gb2312";
24.
25. // 導出excel文件
26. strWriter = new System.IO.StringWriter();
27. htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
28.
29. // 爲了解決dgData中可能進行了分頁的狀況,須要從新定義一個無分頁的DataGrid
30. dgExport = new System.Web.UI.WebControls.DataGrid();
31. dgExport.DataSource = dtData.DefaultView;
32. dgExport.AllowPaging = false;
33. dgExport.DataBind();
34.
35. // 返回客戶端
36. dgExport.RenderControl(htmlWriter);
37. curContext.Response.Clear();
38. curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString());
39. curContext.Response.End();
40. }
41.}