This method does not use redundant Excel databases, which is concise.
In addition, you can control the output format, such as changing the header. Record it.
/// <Summary>
/// Export EXCEL from datatable
/// </Summary>
/// <Param name = "DT"> </param>
/// <Param name = "FILENAME"> </param>
Private Void Createexcel (datatable DT, String Filename)
{
Httpresponse resp;
Resp = Page. response;
Resp. contentencoding = System. Text. encoding. getencoding ( " Gb2312 " );
Resp. appendheader ( " Content-Disposition " , " Attachment; filename = " + Filename );
String Colheaders = "" , Ls_item = "" ;
/// /Define table objects and row objects, and use dataset to initialize their values.
// Datatable dt = Ds. Tables [0];
Datarow [] myrow = DT. Select (); // Data filtering can be achieved in the form of DT. Select ("ID> 10 ").
Int I = 0 ;
Int Cl = DT. Columns. count;
// Obtain the titles of each column in the data table. The headers are separated by T. A carriage return is followed by the last column title.
For (I = 0 ; I < Cl; I ++ )
{
If (I = (CL - 1 )) // Add n to the last column.
{
Colheaders + = DT. Columns [I]. Caption. tostring () + " \ N " ;
}
Else
{
Colheaders + = DT. Columns [I]. Caption. tostring () + " \ T " ;
}
}
Resp. Write (colheaders );
//Write the obtained data to the HTTP output stream
// Process Data row by row
Foreach (Datarow row In Myrow)
{
// The data in the current row is written to the HTTP output stream, and ls_item is left blank for downstream data
For (I = 0 ; I < Cl; I ++ )
{
If (I = (CL - 1 )) // Add n to the last column.
{
Ls_item + = Row [I]. tostring () + " \ N " ;
}
Else
{
Ls_item + = Row [I]. tostring () + " \ T " ;
}
}< br> resp. write (ls_item);
ls_item = " " ;
}
Resp. End ();
}
Protected VoidBtnout_click (ObjectSender, eventargs E)
{
Datatable dt=Dbutility. oledbhelper. executedt ("Select * From t_customer");
Createexcel (DT,"Hello.xls");
}