First, pass the DataGrid as a parameter and convert the DataGrid to excel
Public bool toexcel (system. Web. UI. Control CTL)
{
Try
{
Httpcontext. Current. response. appendheader ("content-disposition", "attachment?filename=excel.xls ");
Httpcontext. Current. response. charset = "UTF-8 ";
Httpcontext. Current. response. contentencoding = system. Text. encoding. default;
Httpcontext. Current. response. contenttype = "application/MS-excel"; // image/JPEG; text/html; image/GIF; VND. MS-Excel/MSWord
CTL. Page. enableviewstate = false;
System. Io. stringwriter Tw = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter hW = new system. Web. UI. htmltextwriter (TW );
CTL. rendercontrol (HW );
Httpcontext. Current. response. Write (TW. tostring ());
Httpcontext. Current. response. End ();
Return true;
}
Catch (exception E)
{
_ Errormsg = E. message;
Return false;
}
}
Second, export dataset directly to excel
Public void createexcel (Dataset ds, string typeid, string filename)
{
Httpresponse resp;
Resp = page. response;
Resp. contentencoding = system. Text. encoding. getencoding ("gb2312 ");
Resp. appendheader ("content-disposition", "attachment; filename =" + filename );
Resp. charset = "UTF-8 ";
String colheaders = "", ls_item = "";
Int I = 0;
// Define the table object and row object, and use dataset to initialize its value
Datatable dt = Ds. Tables [0];
Datarow [] myrow = DT. Select ("");
// When typeid = "1", the exported file is in Excel format; When typeid = "2", the exported file is in XML format.
If (typeid = "1 ")
{
Resp. contenttype = "application/MS-excel"; // image/JPEG; text/html; image/GIF; VND. MS-Excel/MSWord
// Obtain the titles of each column in the data table, separated by \ t, and a carriage return is added after the title of the last column.
For (I = 0; I <DT. Columns. Count-1; I ++)
Colheaders + = DT. Columns [I]. Caption. tostring () + "\ t ";
Colheaders + = DT. Columns [I]. Caption. tostring () + "\ n ";
// Write the obtained data to the HTTP output stream
Resp. Write (colheaders );
// Process data row by row
Foreach (datarow row in myrow)
{
// In the current row, data is obtained one by one, separated by \ t, and carriage return \ n is added at the end
For (I = 0; I <DT. Columns. Count-1; I ++)
Ls_item + = row [I]. tostring (). Replace ("\ t", "") + "\ t ";
Ls_item + = row [I]. tostring (). Replace ("\ t", "") + "\ n ";
// Write the data in the current row to the HTTP output stream, and leave ls_item empty for downstream data
Resp. Write (ls_item );
Ls_item = "";
}
}
Else
{
If (typeid = "2 ")
{
// Export XML data directly from dataset and write it to the HTTP output stream
Resp. Write (Ds. getxml ());
}
}
// Write the data in the buffer to the HTTP header file
Resp. End ();
}