.NET 将数据输出到WORD、EXCEL、TXT、HTM
其實,利用ASP.NET輸出指定內容的WORD、EXCEL、TXT、HTM等類型的文檔很容易的。主要分為三步來完成。
一、定義文檔類型、字符編碼
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
//下面這行很重要, attachment 參數表示作為附件下載,您可以改成 online在線打開
//filename=FileFlow.xls 指定輸出文件的名稱,注意其擴展名和指定文件類型相符,可以為:.doc || .xls || .txt ||.htm
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentType指定文件類型 可以為application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他瀏覽器可直接支持文檔
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
二、定義一個輸入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
三、將目標數據綁定到輸入流輸出
this.RenderControl(oHtmlTextWriter);
//this 表示輸出本頁,你也可以綁定datagrid,或其他支持obj.RenderControl()屬性的控件
Response.Write(oStringWriter.ToString());
Response.End();
?
?
示例:
?
? /// <summary>
??????? /// 導出數據到Excel表的方法
??????? /// <param name="dt">DataTable數據源</param>
??????? /// <param name="title">生成的Excel文件名</param>
??????? /// </summary>
??????? public static void Export(System.Data.DataTable dt, string title)
??????? {
??????????? StringWriter sw = new StringWriter();
??????????? foreach (System.Data.DataColumn col in dt.Columns)
??????????? {
??????????????? sw.Write(col.Caption + "\t");
??????????? }
??????????? sw.WriteLine();
??????????? foreach (System.Data.DataRow row in dt.Rows)
??????????? {
??????????????? for (int i = 0; i < dt.Columns.Count; i++)
??????????????? {
??????????????????? sw.Write(row[i].ToString() + "\t");
??????????????? }
??????????????? sw.WriteLine();
??????????? }
??????????? sw.Close();
??????????? string filename = System.Web.HttpUtility.UrlPathEncode(title) + DateTime.Now.ToString("yyyyMMdd") + ".xls";
??????????? HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename);
??????????? HttpContext.Current.Response.ContentType = "application/ms-excel";
??????????? HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
??????????? HttpContext.Current.Response.Write(sw);
??????????? HttpContext.Current.Response.End();
??????? }
轉載于:https://www.cnblogs.com/_zjl/archive/2012/06/18/2553822.html
總結
以上是生活随笔為你收集整理的.NET 将数据输出到WORD、EXCEL、TXT、HTM的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: e缴通怎么注册
- 下一篇: Git related