Copy codeThe Code is as follows :///
/// Export the data in the DataTable to the specified Excel File
///
/// Web Page Object
/// The DataTable object that contains the exported data
/// Excel file name
Public static void Export (System. Web. UI. Page page, System. Data. DataTable tab, string FileName)
{
System. Web. HttpResponse httpResponse = page. Response;
System. Web. UI. WebControls. DataGrid dataGrid = new System. Web. UI. WebControls. DataGrid ();
DataGrid. DataSource = tab. DefaultView;
DataGrid. AllowPaging = false;
DataGrid. HeaderStyle. BackColor = System. Drawing. Color. Green;
DataGrid. HeaderStyle. HorizontalAlign = HorizontalAlign. Center;
DataGrid. HeaderStyle. Font. Bold = true;
DataGrid. DataBind ();
HttpResponse. appendHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. urlEncode (FileName, System. text. encoding. UTF8); // filename = "*. xls ";
HttpResponse. ContentEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
HttpResponse. ContentType = "application/ms-excel ";
System. IO. StringWriter tw = new System. IO. StringWriter ();
System. Web. UI. HtmlTextWriter hw = new System. Web. UI. HtmlTextWriter (tw );
DataGrid. RenderControl (hw );
String filePath = page. Server. MapPath ("..") + "// Files //" + FileName;
System. IO. StreamWriter sw = System. IO. File. CreateText (filePath );
Sw. Write (tw. ToString ());
Sw. Close ();
DownFile (httpResponse, FileName, filePath );
HttpResponse. End ();
}
Private static bool DownFile (System. Web. HttpResponse Response, string fileName, string fullPath)
{
Try
{
Response. ContentType = "application/octet-stream ";
Response. AppendHeader ("Content-Disposition", "attachment; filename =" +
HttpUtility. UrlEncode (fileName, System. Text. Encoding. UTF8) + "; charset = GB2312 ");
System. IO. FileStream fs = System. IO. File. OpenRead (fullPath );
Long fLen = fs. Length;
Int size = 102400; // download data at the same time every k
Byte [] readData = http://www.jb51.net/yongle_tianya/archive/2011/10/24/new byte [size]; // specify the buffer size
If (size> fLen) size = Convert. ToInt32 (fLen );
Long fPos = 0;
Bool isEnd = false;
While (! IsEnd)
{
If (fPos + size)> fLen)
{
Size = Convert. ToInt32 (fLen-fPos );
ReadData = http://www.jb51.net/yongle_tianya/archive/2011/10/24/new byte [size];
IsEnd = true;
}
Fs. Read (readData, 0, size); // Read a compressed Block
Response. BinaryWrite (readData );
FPos + = size;
}
Fs. Close ();
System. IO. File. Delete (fullPath );
Return true;
}
Catch
{
Return false;
}
}