/**
Export Excel files, file operations using Apache POI framework
**/
Public Static<E>voidExportexcel (httpservletresponse response, string[] header,int[] column, string[] fileNames, list<e>list, String excelname) {//Create a workbookHssfworkbook WB =NewHssfworkbook ();//Create a sheetHssfsheet sheet =Wb.createsheet (excelname); Hssfrow HeaderRow= Sheet.createrow (0); Hssfrow Contentrow=NULL;//Set Title for(inti = 0; i < header.length; i++) {Headerrow.createcell (i). Setcellvalue (Header[i]);if(Column! =NULL) {sheet.setcolumnwidth (I, Column[i]);}}Try {intSize =list.size (); for(inti = 0; i < size; i++) {Contentrow= Sheet.createrow (i + 1);//get each objectE o =List.get (i); Class CLS=O.getclass (); for(intj = 0; J < Filenames.length; J + +) {String fieldName= filenames[j].substring (0, 1). toUpperCase () + filenames[j].substring (1); Method GetMethod;Try{GetMethod= Cls.getmethod ("Get" +fieldName); Object value=Getmethod.invoke (o);if(Value! =NULL) {Contentrow.createcell (j). Setcellvalue (Value.tostring ());}} Catch(nosuchmethodexception e) {Contentrow.createcell (j). Setcellvalue (i+1);}}}} Catch(IllegalArgumentException e) {logger.error ("", E);} Catch(illegalaccessexception e) {logger.error ("", E);} Catch(InvocationTargetException e) {logger.error ("", E);} Catch(SecurityException e) {logger.error ("", E);} OutputStream OS=NULL;Try{response.reset (); Response.AddHeader ("Content-disposition", "attachment;filename=" +NewString ((Excelname + ". xlsx"). GetBytes (), "Iso-8859-1")); Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8"); OS=Response.getoutputstream (); wb.write (OS);} Catch(Exception e) {logger.error ("", E);} finally{ioutil.close (OS);}}
/**
Export CSV file, file operations using Univocity framework
**/
Public Static<E>voidExportcsv (httpservletresponse response, string[] header,int[] column, string[] fileNames, list<e>list, String csvname) {outputstream OS=NULL; Csvwriter writer=NULL;Try{response.reset (); Response.AddHeader ("Content-disposition", "attachment;filename=" +NewString ((Csvname + ". csv"). GetBytes (), "Iso-8859-1")); Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8"); OS=Response.getoutputstream (); writer=NewCsvwriter (OS,Newcsvwritersettings ()); Writer.writeheaders (header) ;intSize =list.size (); for(inti = 0; i < size; i++) {string[] content=NewString[size];//get each objectE o =List.get (i); Class CLS=O.getclass (); for(intj = 0; J < Filenames.length; J + +) {String fieldName= filenames[j].substring (0, 1). toUpperCase () + filenames[j].substring (1); Method GetMethod;Try{GetMethod= Cls.getmethod ("Get" +fieldName); Object value=Getmethod.invoke (o);if(Value! =NULL) {Content[i]=value.tostring ();}} Catch(nosuchmethodexception e) {Content[i]= "";}} Writer.writerow (content);}} Catch(Exception e) {logger.error ("", E);} finally{writer.close (); ioutil.close (OS);}}
JavaBean data export Excel and CSV file