ASP. NET exports data to Excel

Source: Internet
Author: User

This article describes how to use the DataTable to export excel in C #, as for other export methods, this is not introduced here!

1. Home page reads data from the database and gets a DataTable:

DataTable dt = helperexecutesql.query ("select Id,name,author,newscontent,indate from Newsinfo" ). tables[0];

2. Using the StringWriter class: Writes information to a string (its namespace is: System.IO)

PrivateStringWriter getstringwriter (DataTable dt) {StringWriter SW=NewStringWriter (); //read the column name, or you can customize the column name (that is, export the Excel header)//foreach (DataColumn dc in dt. Columns)//{SW. Write (DC. ColumnName + "\ t");}
//table header, customizingSw. Write ("serial number \ t"); Sw. Write ("News name \ t"); Sw. Write ("author \ t");SW. Write ("news content \ t"); Sw. Write ("upload time \ t");//read column values, re-lineSW. Write (SW. NewLine); if(dt! =NULL) { foreach(DataRow Drinchdt. Rows) { for(inti =0; i < dt. Columns.count; i++) { SW. Write (Dr[i]. ToString ()+"\ t"); } SW. Write (SW. NewLine); }} SW. Close (); returnSW; }

3. Excelimport (DT, "News list");

protected void Excelimport (DataTable dt, string exportfilename)    {        StringWriter sw = getstringwriter (DT);        Current encoding          HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312");        Encode the file name of the output          string filename = Httputility.urlencode (exportfilename, System.Text.Encoding.UTF8);        File name          string str = "Attachment;filename=" + filename + ". xls";        Put the file header output, this file header activates the file download box          HttpContext.Current.Response.AppendHeader ("content-disposition", str);//http header file          HttpContext.Current.Response.ContentType = "Application/ms-excel";        This. Page.enableviewstate = false;        Response.Write (SW);        Response.End ();    }

  

ASP. NET exports data to Excel

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.