Complete program:
One: Call method: Createexcel (NEWDT, "Application/ms-excel", "FileName");
/// <summary> ///data in a DataTable is exported to Excel and downloaded/// </summary> /// <param name= "DT" >the DataTable to export</param> /// <param name= "FileType" >type</param> /// <param name= "FileName" >the file name of Excel</param> Public voidCreateexcel (DataTable DT,stringFileType,stringFileName) {response.clear (); Response.Charset="UTF-8"; Response.Buffer=true; Response.ContentEncoding= System.Text.Encoding.GetEncoding ("GB2312"); Response.appendheader ("content-disposition","attachment;filename=\ ""+ System.Web.HttpUtility.UrlEncode (FileName, System.Text.Encoding.UTF8) +". Xls\ ""); Response.ContentType=FileType; stringColheaders =string. Empty; stringLs_item =string. Empty; Datarow[] Myrow=dt. Select (); inti =0; intCL =dt. Columns.count; //Write Method One//write information such as titleLs_item + = Label2.Text +"\t\t\t\n\n"; Response.Output.Write (Ls_item); Ls_item=string. Empty; Ls_item+ = Txtstart.text +"\t\t\t"; Ls_item+ = Dropenterprise.selecteditem +"\ n"; Response.Output.Write (Ls_item); Ls_item=string. Empty; //Write segment title for(i =0; I < CL; i++) { if(i = = (CL-1) ) {Ls_item+ = dt. Columns[i]. Columnname.tostring () +"\ n"; } Else{Ls_item+ = dt. Columns[i]. Columnname.tostring () +"\ t"; }} Response.Output.Write (Ls_item); Ls_item=string. Empty; foreach(DataRow rowinchmyrow) { for(i =0; I < CL; i++) { if(i = = (CL-1) ) {Ls_item+ = Row[i]. ToString () +"\ n"; } Else{Ls_item+ = Row[i]. ToString () +"\ t"; } } //write on one lineResponse.Output.Write (Ls_item); Ls_item=string. Empty; } Response.Output.Flush (); Response.End (); }
How to export Excel from asp: Using Response to export Excel