/// /// Export data in DataTable to the specified Excel file /// summary> /// web page object param> /// < Param name = "tab"> contains DataTable objects of exported data param> /// Excel file Name param> 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 (); sys Tem.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) {rate {response.contenttype = "Application / OcT-stream";