頁面導出到Excel、Word、txt

  1. 一、定義文檔類型、字符編碼   
  2.   
  3. Response.Clear();    
  4. Response.Buffer= true;    
  5. Response.Charset="utf-8";   
  6.   
  7. //下面這行很重要, attachment 參數表示作爲附件下載,您可以改成 online在線打開   
  8.   
  9. //filename=FileFlow.xls 指定輸出文件的名稱,注意其擴展名和指定文件類型相符,可以爲:.doc || .xls || .txt ||.htm   
  10.   
  11. Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");   
  12. Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");   
  13.   
  14. //Response.ContentType指定文件類型 可以爲application/ms-excel || application/ms-word || application/ms-txt || application/ms-Html || 或其他瀏覽器可直接支持文檔   
  15.   
  16. Response.ContentType = "application/ms-excel";   
  17. this.EnableViewState = false;    
  18.   
  19. 二、定義一個輸入流   
  20.   
  21. System.IO.StringWriter oStringWriter = new System.IO.StringWriter();    
  22. System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);    
  23.   
  24. 三、將目標數據綁定到輸入流輸出   
  25.   
  26. this.RenderControl(oHtmlTextWriter);    
  27.   
  28. //this 表示輸出本頁,你也可以綁定datagrid,或其他支持obj.RenderControl()屬性的控件   
  29.   
  30. Response.Write(oStringWriter.ToString());   
  31. Response.End();    
  32. 注意:有控件,有圖片就會出錯,只能用於導出較簡單的網頁,如果需要導出的頁面中有css文件鏈接,導出文件時會彈出提示“無法找到xxx.css文件”,因此需要把頁面中用到的樣式從css樣式文件中複製出來,寫在頁面中。
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章