Copy codeThe Code is as follows:
Public static void CreateExcel (DataSet ds)
{
String filename = DateTime. Now. ToString ("yyyyMMddHHmmssff") + ". xls ";
HttpContext. Current. Response. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
HttpContext. Current. Response. AppendHeader ("Content-Disposition", "attachment; filename =" + filename );
String colHeaders = "", ls_item = "";
// Define the table object and row object, and use DataSet to initialize the value.
DataTable dt = ds. Tables [0];
DataRow [] myRow = dt. Select (); // you can filter data 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, separated by \ t, and a carriage return is added after the title of the last column.
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 ";
}
}
HttpContext. Current. Response. Write (colHeaders );
// Write the obtained data to the HTTP output stream
// Process data row by row
Foreach (DataRow row in myRow)
{
// Write the data in the current row to the HTTP output stream, and leave ls_item empty 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 ";
}
}
HttpContext. Current. Response. Write (ls_item );
Ls_item = "";
}
HttpContext. Current. Response. End ();
}