///
Export data from a DataTable to a specified Excel file
///
Web Page objects
The DataTable object that contains the exported data
The name of the Excel file
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 every 100K
byte[] ReadData = http://www.jb51.net/yongle_tianya/archive/2011/10/24/new byte[size];//The size of the specified buffer
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);/reading a compressed block
Response.BinaryWrite (ReadData);
Fpos+=size;
}
Fs. Close ();
System.IO.File.Delete (FullPath);
return true;
}
Catch
{
return false;
}
}