STRUTS2 configuration file
<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/dtds/ Struts-2.0.dtd "><struts> < package name="Vclassenroll" extends= "json-default" namespace="/vclassenroll"> <action name= "op/*" class=" Com.xxx.action.VclassEnrollOperateAction " method=" {1} "> <result name="Excel" type="Stream"> <param name="ContentType">Application/vnd.ms-excel</param> <param name="InputName">Excelstream</param> <param name="Contentdisposition">Filename= "${filename}.xls"</param> <param name="buffersize">1024</param> </result> </Action> </Package ></struts>
Struts2 the corresponding action
ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;ImportJava.text.SimpleDateFormat;ImportJava.util.ArrayList;ImportJava.util.Date;ImportJava.util.List;ImportJava.util.Random;ImportJavax.annotation.Resource; Public class vclassenrolloperateaction extends baseaction { Private Static Final LongSerialversionuid =-941593970307742358L@Resource PrivateVclassenrollservice Vclassenrollservice;PrivateVclassenroll Vclassenroll;PrivateString classId;PrivateInputStream Excelstream;PrivateString FileName; PublicStringExportexcel() {if(Vclassenroll = =NULL) {Vclassenroll =NewVclassenroll (); }if(Stringutils.isnotnull (CLASSID)) {vclassenroll.setvclass_id (Integer.parseint (classId)); list<vclassenroll> list = Vclassenrollservice.getlist (Vclassenroll);//Convert OutputStream to InputStreamBytearrayoutputstream out =NewBytearrayoutputstream (); list<string> columns =NewArraylist<string> (); Columns.Add ("Serial number"); Columns.Add ("Name"); Columns.Add ("Grade"); Columns.Add ("Class"); Columns.Add ("Phone"); String CNAME ="";if(List! =NULL&& list.size () >0) {cname = List.get (0). Getcname (); } jxlexcelutils.getexcelstream (out, list,"Registration record-"+cname, columns); Excelstream =NewBytearrayinputstream (Out.tobytearray ()); FileName = Createfilename (); }return "Excel"; }/** * Creates a file name with the format of a number of milliseconds + 4-bit random numbers, without the extension * @return file name */ Public StaticStringCreatefilename() {StringBuffer SB =NewStringBuffer (); Date Date =NewDate ();//Get month/day secondsSb.append (NewSimpleDateFormat ("YYYYMMDDHHMMSS"). Format (date);//MSString milli = string.valueof (date.gettime ()% +); while(Milli.length () <3) {milli ="0"+ Milli; } sb.append (milli);//Four-bit random numberString rondom = string.valueof (NewRandom (). Nextint (10000)); while(Rondom.length () <4) {Rondom ="0"+ Rondom; } sb.append (Rondom);returnSb.tostring (); } }
Tool class
ImportJava.io.ByteArrayOutputStream;ImportJava.io.OutputStream;ImportJava.io.UnsupportedEncodingException;ImportJava.util.List;ImportJava.util.Map;ImportJavax.servlet.http.HttpServletResponse;ImportJxl. Sheetsettings;ImportJxl. Workbook;ImportJxl.format.Alignment;ImportJxl.format.Colour;ImportJxl.format.VerticalAlignment;ImportJxl.write.Label;ImportJxl.write.WritableCellFormat;ImportJxl.write.WritableFont;ImportJxl.write.WritableSheet;ImportJxl.write.WritableWorkbook; Public class jxlexcelutils { /** * @author * @param objdata Export an array of contents * @param sheetname The name of the exported sheet *
@param columns export An array of headers for Excel *
@return *
/ Public Static int Getexcelstream(Bytearrayoutputstream OS, list<vclassenroll> List, String sheetname,list<string> columns) {intFlag =0;//Declaration Workbook Jxl.write.WritableWorkbookWritableworkbook workbook;Try{//Create a writable Excel workbook based on the file object passed inWorkbook = Workbook.createworkbook (OS);/ * * Create a worksheet, sheetname the name of the worksheet, "0" as the first sheet * when you open Excel, you will see 3 sheet, "Sheet1, Sheet2, Sheet3" in the lower left corner. So the "0" in the code is Sheet1, and the other one by one corresponds. * Createsheet (sheetname, 0) One is the name of the worksheet and the other is the position of the worksheet in the workbook */Writablesheet ws = Workbook.createsheet (SheetName,0); sheetsettings ss = Ws.getsettings (); Ss.setverticalfreeze (1);//Freeze table headerWritablefont font1 =NewWritablefont (Writablefont.createfont ("Microsoft Jas Black"),Ten, Writablefont.bold); Writablefont Font2 =NewWritablefont (Writablefont.createfont ("Microsoft Jas Black"),9, Writablefont.no_bold); Writablecellformat WCF =NewWritablecellformat (FONT1); Writablecellformat WCF2 =NewWritablecellformat (Font2); Writablecellformat WCF3 =NewWritablecellformat (Font2);//Set style, font //Create a cell style //writablecellformat WCF = new Writablecellformat (); //Background colorWcf.setbackground (Jxl.format.Colour.YELLOW); Wcf.setalignment (Alignment.centre);//Parallel centeringWcf.setverticalalignment (Verticalalignment.centre);//Vertical CenterWcf3.setalignment (Alignment.centre);//Parallel centeringWcf3.setverticalalignment (Verticalalignment.centre);//Vertical CenterWcf3.setbackground (Colour.light_orange); Wcf2.setalignment (Alignment.centre);//Parallel centeringWcf2.setverticalalignment (Verticalalignment.centre);//Vertical Center / * * This is the cell content Center display * There are many more styles * *Wcf.setalignment (Alignment.centre);//Determine if the table header array has data if(Columns! =NULL&& columns.size () >0) {//Loop write to table header for(inti =0; I < columns.size (); i++) {/ * * Add cell (cell) content Addcell () * Add Label Object label () * Data type has There are many kinds of types that you need to import into what type * such as: Jxl.write.DateTime, Jxl.write.Number, Jxl.write.Label * Label (i, 0, columns[i], WCF) * Where I is a column, 0 is a row, columns[i] is data, and WCF is a style * together it means columns[ I] add to the first row (row, column subscript is starting from 0) column I, style why the color content is centered */Ws.addcell (NewLabel (I,0, Columns.get (i), WCF)); }//Determine if there is data in the table if(List! =NULL&& list.size () >0) {//Loop writes data to the table for(inti =0; I < list.size (); i++) {intj = i+1; Ws.addcell (NewLabel (0, J, i+"")); Ws.addcell (NewLabel (1, J, List.get (i). Getstu_name ()); Ws.addcell (NewLabel (2, J, List.get (i). Getgradeid () +"")); Ws.addcell (NewLabel (3, J, List.get (i). GetClassID () +"")); Ws.addcell (NewLabel (4, J, List.get (i). Gettelephone () +"")); } }Else{flag =-1; }//write Exel worksheetWorkbook.write ();//Close the Excel workbook objectWorkbook.close ();//Close streamOs.flush (); Os.close (); OS =NULL; } }Catch(IllegalStateException e) {System.err.println (E.getmessage ()); }Catch(Exception ex) {flag =0; Ex.printstacktrace (); }returnFlag } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Struts JXL Export Excel