asp.net LINQ to export data to Excel code _ practical Tips

Source: Internet
Author: User
Some time ago, a friend. To complete this feature, the data is imported into the DataGrid and exported to Excel. This is really superfluous.
Solution:
read out data through LINQ and write directly to the data stream
The code is as follows:
Copy Code code 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" defaults to the separator between two columns in 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.