標籤:style blog http color io os 使用 ar 檔案
Web項目中,很多時候須要實現將查詢的資料集匯出為Excel、Word等文檔的功能,很多時候不太希望在工程中添加對Office組件相關的DLL的引用,甚至有時候受到Office不同版本的影響,導致在不同的伺服器上部署後功能受限,或和其它項目衝突,那麼,使用這種簡單粗暴的方式,可能會解決部分猿類的煩惱憂愁。
public static bool DataTableToExcel(System.Data.DataTable dataTable, string fileName){ if (dataTable == null) return false; if (string.IsNullOrWhiteSpace(fileName)) return false; HttpResponse httpResponse = HttpContext.Current.Response; //ContentType 指定檔案類型可以為application/ms-excel、application/ms-word、application/ms-txt、application/ms-html httpResponse.ContentType = "application/vnd.ms-excel"; httpResponse.ContentEncoding = Encoding.UTF8; //context.Response.Charset = "GB2312"; //"attachment"表示作為附件下載,可以改成"online"線上開啟。"filename=xxx.xls"指定輸出檔案名,其副檔名和檔案類型相符,可為:.doc .xls .txt .html httpResponse.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + ".xls"); //匯出檔案 System.IO.StringWriter sw = sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); //為瞭解決dgData中可能進行了分頁的情況,需要重新定義一個無分頁的DataGrid System.Web.UI.WebControls.DataGrid datagrid = datagrid = new System.Web.UI.WebControls.DataGrid(); datagrid.DataSource = dataTable.DefaultView; datagrid.AllowPaging = false; datagrid.DataBind(); //返回用戶端 datagrid.RenderControl(htw); httpResponse.Write(sw.ToString()); httpResponse.End(); return true;}
以上代碼中指定 ContentType 屬性為Excel,即匯出Excel格式的檔案,稍作修改亦可匯出其它類型的檔案,不做贅述。當然,也可以把功能函數寫的更為通用,通過參數判斷匯出哪種檔案類型,有需要的自己進行改進和最佳化吧。
另外,在匯出檔案名稱為中文的時候,可能會出現亂碼,因此需要使用UrlEncode編碼一下。
利用HttpResponse將DataTable資料匯出為Excel/Word/Txt/Html文檔