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.