Private Static Stream exportdatatabletoexcel (datatable sourcetable, String Sheetname) {hssfworkbook workbook = New Hssfworkbook (); memorystream MS = New Memorystream (); isheet Sheet = Workbook. createsheet (sheetname); irow headerrow = Sheet. createrow ( 0 ); Foreach (Datacolumn Column In Sourcetable. columns) {headerrow. createcell (column. ordinal). setcellvalue (column. columnname );} Int Rowindex = 1 ; Foreach (Datarow row In Sourcetable. Rows) {irow datarow = Sheet. createrow (rowindex ); Foreach (Datacolumn ColumnIn Sourcetable. columns) {datarow. createcell (column. ordinal). setcellvalue (row [column]. tostring ();} rowindex ++ ;} Workbook. Write (MS); Ms. Flush (); Ms. Position = 0 ; Sheet = Null ; Headerrow = Null ; Workbook = Null ; Return MS ;} /// <Summary> /// Datatable export to excel file [winfrom] /// </Summary> /// <Param name = "dtsource"> Source able </Param> /// <Param name = "strheadertext"> Header text </Param> /// <Param name = "strfilename"> Save location </Param> Public Static Void Export (datatable dtsource, String Strheadertext, String Strfilename ){ Using (Memorystream MS = Export (dtsource, strheadertext )){ Using (Filestream FS = New Filestream (strfilename, filemode. Create, fileaccess. Write )){ Byte [] DATA = Ms. toarray (); FS. Write (data, 0 , Data. Length); FS. Flush ();}}} /// <Summary> /// Export Excel [web] From datatable /// </Summary> /// <Param name = "sourcetable"> Datatable to export data </Param> /// <Param name = "FILENAME"> Excel worksheet name </Param> /// <Returns> Excel worksheet </Returns> Public Static Void Exportdatatabletoexcel (datatable sourcetable, String Filename, String Sheetname ){ Try {Memorystream MS = Exportdatatabletoexcel (sourcetable, sheetname) As Memorystream; httpcontext. Current. response. contentencoding = System. Text. encoding. getencoding ( " UTF-8 " ); Httpcontext. Current. response. appendheader ( " Content-Disposition " , " Attachment; filename = " + System. web. httputility. urlencode (filename, system. text. encoding. utf8); httpcontext. current. response. binarywrite (Ms. toarray (); httpcontext. current. response. end (); Ms. close (); MS = Null ;} Catch (Exception ex) {httpcontext. Current. response. Write (Ex );}}
The plug-in npoi is used here.