Code for exporting data to excel by Asp.net LINQ

Source: Internet
Author: User

A friend of mine tried to import the data to the DataGrid and then export it to excel to complete this function. This is exactly the same thing.
Solution:
Read data through LINQ and directly write data into the data stream
Code As follows: Copy code The Code is as follows: public partial class datatoexcel: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
Dataaccess. dataclassesdatacontext DB = new dataclassesdatacontext ();
VaR Qu = from T in dB. txlinfos
Select T;
Response. appendheader ("content-disposition", "attachment?filename=result.xls ");
Response. contenttype = "application/MS-excel ";
Response. charset = "gb2312 ";
Response. contentencoding = encoding. getencoding ("gb2312 ");
System. Io. stringwriter writer = new system. Io. stringwriter ();
Foreach (txlinfo item in Qu)
{
Writer. Write (item. gqname );
Writer. Write ("\ t ");
Writer. Write (item. gqid );
Writer. writeline ();
}
Response. Write (writer. tostring ());
Response. End ();
}
}

Note: "\ t" is the separator between two columns in Excel by default.

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.