This article describes how to use the DataTable to export excel in C #, as for other export methods, this is not introduced here!
1. Home page reads data from the database and gets a DataTable:
DataTable dt = helperexecutesql.query ("select Id,name,author,newscontent,indate from Newsinfo" ). tables[0];
2. Using the StringWriter class: Writes information to a string (its namespace is: System.IO)
PrivateStringWriter getstringwriter (DataTable dt) {StringWriter SW=NewStringWriter (); //read the column name, or you can customize the column name (that is, export the Excel header)//foreach (DataColumn dc in dt. Columns)//{SW. Write (DC. ColumnName + "\ t");}
//table header, customizingSw. Write ("serial number \ t"); Sw. Write ("News name \ t"); Sw. Write ("author \ t");SW. Write ("news content \ t"); Sw. Write ("upload time \ t");//read column values, 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; }
3. Excelimport (DT, "News list");
protected void Excelimport (DataTable dt, string exportfilename) { StringWriter sw = getstringwriter (DT); Current encoding HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312"); Encode the file name of the output string filename = Httputility.urlencode (exportfilename, System.Text.Encoding.UTF8); File name string str = "Attachment;filename=" + filename + ". xls"; Put the file header output, this file header activates the file download box HttpContext.Current.Response.AppendHeader ("content-disposition", str);//http header file HttpContext.Current.Response.ContentType = "Application/ms-excel"; This. Page.enableviewstate = false; Response.Write (SW); Response.End (); }
ASP. NET exports data to Excel