In a Web project, it is often necessary to implement the ability to export a query's dataset into a document such as Excel, Word, and many times you do not want to add references to the DLLs associated with Office components in your project, or even be affected by different versions of Office. Result in limited functionality after deployment on different servers, or conflict with other projects, the use of this simple and brutal approach may solve some of the apes ' disturbing worries.
Public Static BOOLDatatabletoexcel (System.Data.DataTable DataTable,stringfileName) { if(DataTable = =NULL)return false; if(string. Isnullorwhitespace (FileName))return false; HttpResponse HttpResponse=HttpContext.Current.Response; //ContentType Specifies that the file type can be Application/ms-excel, Application/ms-word, Application/ms-txt, application/ms-htmlHttpresponse.contenttype ="Application/vnd.ms-excel"; HttpResponse.ContentEncoding=Encoding.UTF8; //context. Response.Charset = "GB2312"; //"attachment" means to download as an attachment, you can change it to "online" to open on line. "Filename=xxx.xls" specifies the output file name with an extension that matches the file type:. doc. xls. txt. htmlHttpresponse.appendheader ("content-disposition","attachment; Filename="+ Httputility.urlencode (fileName, Encoding.UTF8) +". xls"); //Export FileSystem.IO.StringWriter SW = SW =NewSystem.IO.StringWriter (); System.Web.UI.HtmlTextWriter HTW=NewSystem.Web.UI.HtmlTextWriter (SW); //To resolve a possible paging situation in dgdata, you need to redefine a DataGrid with no pagingSystem.Web.UI.WebControls.DataGrid DataGrid = DataGrid =NewSystem.Web.UI.WebControls.DataGrid (); Datagrid. DataSource=Datatable.defaultview; Datagrid. AllowPaging=false; Datagrid. DataBind (); //Back to clientDataGrid. RenderControl (HTW); HttpResponse.Write (SW. ToString ()); Httpresponse.end (); return true;}
The above code specifies that the ContentType attribute is Excel, that is, the export of Excel format files, minor changes can also export other types of files, do not repeat. Of course, the function function can also be written more general, through the parameters to determine which type of file to export, it is necessary to improve and optimize it.
In addition, when the export file name is called Chinese, there may be garbled characters, so you need to use UrlEncode encoding.
Export DataTable data as excel/word/txt/html document using HttpResponse