1. Methods
PrivateStringWriter getstringwriter (DataTable dt) {StringWriter SW=NewStringWriter (); //Read Column name foreach(DataColumn DCinchdt. Columns) SW. Write (DC. ColumnName+"\ t"); //Read column values//a re-lineSW. Write (SW. NewLine); if(dt! =NULL) { foreach(DataRow Drinchdt. Rows) { for(inti =0; i < dt. Columns.count; i++) {SW. Write (Dr[i]. ToString ()+"\ t"); } SW. Write (SW. NewLine); }} SW. Close (); returnSW; } protected voidExcelimport (DataTable DT,stringexportfilename) {StringWriter SW=getstringwriter (DT); //Current EncodingHttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312"); //encode the file name of the output stringFileName =Httputility.urlencode (Exportfilename, System.Text.Encoding.UTF8); //file name stringstr ="attachment;filename="+ FileName +". xls"; //put the file header output, this file header activates the file download boxHttpContext.Current.Response.AppendHeader ("content-disposition", str);//HTTP header FileHttpContext.Current.Response.ContentType ="Application/ms-excel"; This. Page.enableviewstate =false; Response.Write (SW); Response.End (); }
2. Call
string " "; = Dbhelpersql.query (SQL). tables[0]; if 0 ) { // export Excel excelimport (DT, DateTime.Now.ToString ( )); }