利用HttpResponse將DataTable資料匯出為Excel/Word/Txt/Html文檔

來源:互聯網
上載者:User

標籤: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文檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.