C#匯出Word [ZT]

來源:互聯網
上載者:User
private void Button13_Click(object sender, System.EventArgs e)
{
this.Datagrid4.Visible=true;
Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename=File1.DOC");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-word";
this.Datagrid4.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter (oStringWriter);
this.Datagrid4.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

在做ASP.NET項目時,會經常遇到要匯出檔案的問題,如將DataGrid中的資料匯出到excel檔案等,經常使用的是Office中的OWC組件,這個組件提供的功能很強大,在一般的項目中都可以滿足當前的需要.但是這個功能強大的組件使用起來卻不是很方便,不但有版本的問題,而且代碼量也相對比較大.如果要利用Respone對象和相關的IO,也可以實現到處excel/word等檔案,而且使用方便.

代碼如下:

System.IO.StringWriter SW = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW);
Page.RenderControl(HTW);
//Page為要匯出的對象,當前是Page,如果是DataGrid,DataList等都可以
Response.Buffer=true;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.