Export data in the DataGrid into the specified Excel file

xiaoxiao2021-03-05  21

///

/// Export data in DataTable to the specified Excel file /// /// web page object /// < Param name = "tab"> contains DataTable objects of 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 (); 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";

转载请注明原文地址:https://www.9cbs.com/read-35630.html

New Post(0)