First enter the controller
@RequestMapping (value= "account/exportwithpopularizedetail") public void Exportwithpopularizedetail ( HttpServletRequest request, HttpServletResponse response,string fnickname,string fpusernickname) {FileInputStream in = Null;outputstream out = null; File File = null;try {response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("application/x-excel;charset= Utf-8 "); String dateTime = dateutil.datetostr (New Date (), "YYYYMMDDHHMMSS"); String fileName = "Promotion Detail Statistics record" + DateTime + ". xls"; Response.setheader ("Content-disposition", "attachment;filename=" + Urlencoder.encode (FileName, "UTF-8")); String Propath = Request.getsession (). Getservletcontext (). Getrealpath ("/"); String path = propath+file.separator+ "Tempfile"; file = new file (path), if (!file.isdirectory ()) {File.mkdir ();} File = new file (path+file.separator+string.valueof (System.currenttimemillis ()) + ". xls"), if (!file.exists ()) { File.createnewfile ();} Userbo.exportpopularizedetailexcel (fnickname,fpusernickname,new fileoutputstream (file)); out = Response.geToutputstream (); in = new FileInputStream (file); byte[] B = new Byte[1024];int I=0;while ((I=in.read (b)) >0) {Out.write ( B, 0, i);} Out.flush ();} catch (IOException e) {e.printstacktrace ();} Finally{try{if (in!=null) {in.close ();} if (out!=null) {out.close ();} if (file!=null) {file.delete ();}} catch (IOException e) {e.printstacktrace ();}}}
The service layer condition queries the list that needs to be printed
public void Exportpopularizedetailexcel (string fnickname,string fpusernickname,outputstream out) {string title = " Promotion of detailed statistics "; Excel Header string[] headers = {"nickname", "Promotion", "Promotion Date"}; String pattern = "Yyyy-mm-dd HH:mm:ss"; Userinfodto userinfodto = new Userinfodto (); Userinfodto.setfnickname (fnickname); Userinfodto.setfrealname ( Fpusernickname); list<popularizedtldto> list = This.getpopularizedetail (userinfodto); excelexportutils<popularizedtldto> util = new excelexportutils<popularizedtldto> (); Util.exportExcel ( Title, headers, list, out, pattern);}
Tool class export Excel to temp file in file output stream
Public classExcelexportutils<t>{@SuppressWarnings ({"Resource"}) Public voidExportexcel (String title, string[] headers, Collection<T>DataSet, OutputStream out, String pattern) { //declaring a working bookHssfworkbook Workbook =NewHssfworkbook (); //Create a tableHssfsheet sheet =Workbook.createsheet (title); //Set table Default column width is 15 bytesSheet.setdefaultcolumnwidth (15); //Generate a styleHssfcellstyle style =Workbook.createcellstyle (); //set these stylesStyle.setfillforegroundcolor (HSSFColor.SKY_BLUE.index); Style.setfillpattern (Hssfcellstyle.solid_foreground); Style.setborderbottom (Hssfcellstyle.border_thin); Style.setborderleft (Hssfcellstyle.border_thin); Style.setborderright (Hssfcellstyle.border_thin); Style.setbordertop (Hssfcellstyle.border_thin); Style.setalignment (Hssfcellstyle.align_center); //Generate a fontHssffont Font =Workbook.createfont (); Font.setcolor (HSSFColor.VIOLET.index); Font.setfontheightinpoints (( Short) 12); Font.setboldweight (Hssffont.boldweight_bold); //apply a font to the current styleStyle.setfont (font); //build and set another styleHssfcellstyle Style2 =Workbook.createcellstyle (); Style2.setfillforegroundcolor (HSSFColor.LIGHT_YELLOW.index); Style2.setfillpattern (Hssfcellstyle.solid_foreground); Style2.setborderbottom (Hssfcellstyle.border_thin); Style2.setborderleft (Hssfcellstyle.border_thin); Style2.setborderright (Hssfcellstyle.border_thin); Style2.setbordertop (Hssfcellstyle.border_thin); Style2.setalignment (Hssfcellstyle.align_center); Style2.setverticalalignment (Hssfcellstyle.vertical_center); //Generate another fontHssffont Font2 =Workbook.createfont (); Font2.setboldweight (Hssffont.boldweight_normal); //apply a font to the current styleStyle2.setfont (Font2); //declaring a paint top-level managerHssfpatriarch Patriarch =Sheet.createdrawingpatriarch (); //define the size and location of annotations, as described in the documentationHssfcomment comment = patriarch.createcomment (NewHssfclientanchor (0, 0, 0, 0, ( Short) 4, 2, ( Short) 6, 5)); //Set Comment ContentComment.setstring (NewHssfrichtextstring ("You can add comments to the POI!") ")); //when you set the comment author, you can see the content in the status bar when you move the mouse over the cell.Comment.setauthor ("Leno"); //Generate table header rowHssfrow row = Sheet.createrow (0); for(inti = 0; i < headers.length; i++) {Hssfcell cell=Row.createcell (i); Cell.setcellstyle (style); hssfrichtextstring text=Newhssfrichtextstring (Headers[i]); Cell.setcellvalue (text); } //iterating through the collection data, producing rows of dataIterator<t> it =Dataset.iterator (); intindex = 0; while(It.hasnext ()) {index++; Row=Sheet.createrow (index); T T=(T) it.next (); //using Reflection, the GetXXX () method is dynamically called to get the attribute value according to the order of the JavaBean property.field[] Fields =T.getclass (). Getdeclaredfields (); for(inti = 0; i < fields.length; i++) {Hssfcell cell=Row.createcell (i); Cell.setcellstyle (Style2); Field field=Fields[i]; Field.setaccessible (true); Try { if(Field.getname (). Equals ("Stop")){ Break; } Object Value=Field.get (t); //coercion type conversion after judging the type of the valueString TextValue =NULL; if(ValueinstanceofInteger) { intIntvalue =(Integer) value; Cell.setcellvalue (Intvalue); } Else if(ValueinstanceofFloat) { floatFvalue =(Float) value; Cell.setcellvalue (Newhssfrichtextstring (string.valueof (Fvalue))); } Else if(ValueinstanceofDouble) { DoubleDvalue =(Double) value; Cell.setcellvalue (Newhssfrichtextstring (string.valueof (Dvalue))); } Else if(ValueinstanceofLong) { LongLongvalue =(Long) value; Cell.setcellvalue (Longvalue); } if(ValueinstanceofBoolean) { BooleanBValue =(Boolean) value; TextValue= "Yes"; if(!bValue) {TextValue= "No"; } cell.setcellvalue (TextValue); } Else if(ValueinstanceofDate) {Date Date=(Date) value; SimpleDateFormat SDF=NewSimpleDateFormat (pattern); TextValue=Sdf.format (date); Cell.setcellvalue (TextValue); }Else{ //other data types are simple to handle as stringsTextValue = value==NULL?"": Value.tostring (); Cell.setcellvalue (TextValue); } //if it is not picture data, use regular expressions to determine whether the TextValue are all made up of numbers//if (TextValue! = null) {//Pattern p = pattern.compile ("^//d+ (//.//d+)? $ ");//Matcher Matcher = P.matcher (TextValue);//if (matcher.matches ()) {// //is a number treated as double//Cell.setcellvalue (double.parsedouble (TextValue));//} else {//hssfrichtextstring richstring = new Hssfrichtextstring (//TextValue);//Hssffont font3 = Workbook.createfont ();//Font3.setcolor (HSSFColor.BLUE.index);//Richstring.applyfont (FONT3);//Cell.setcellvalue (richstring);// }// }}Catch(SecurityException e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } finally { //Clean up Resources } } } Try{workbook.write (out); } Catch(IOException e) {e.printstacktrace (); }finally{ Try{Out.flush (); Out.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
Java Export Excel