Ways to export a DataTable to Word, Excel, txt, htm in. Net

Source: Internet
Author: User

Dt:datatable

Strfile:filename

Strext:type


private void Gridexport (DataTable dt, String strfile, String strext)
{
String strapptype = "";
Switch (strext)
{
Case "XLS":
Strapptype = "Application/ms-excel";
Break
Case "Doc":
Strapptype = "Application/ms-word";
Break
Case "TXT":
Strapptype = "Application/ms-txt";
Break
Case "HTML":
Case "htm":
Strapptype = "application/ms-html";
Break
Default:return;
}
GridView MyGridView = new GridView ();
Mygridview.datasource = DT;
Mygridview.databind ();
HttpContext.Current.Response.Clear ();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader ("Content-type", "text/html; charset=gb2312 ");
HttpContext.Current.Response.AppendHeader ("Content-disposition", String. Format ("attachment;filename={0}.{ 1} ", Httputility.urlencode (strfile,encoding.getencoding (" GB2312 ")), Strext));
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312");
HttpContext.Current.Response.ContentType = Strapptype;
MyGridView.Page.EnableViewState = false;
Second, define an input stream
System.Globalization.CultureInfo Mycitrad = new System.Globalization.CultureInfo ("ZH-CN", true);
System.IO.StringWriter ostringwriter = new System.IO.StringWriter (Mycitrad);
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter (ostringwriter);
Third, bind the target data to the input stream output
Mygridview.rendercontrol (Ohtmltextwriter);
HttpContext.Current.Response.Write (Ostringwriter.tostring ());
HttpContext.Current.Response.End ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.