Java using Apache POI Export-note front end do not use AJAX asynchronous request __java

Source: Internet
Author: User
Tags reflection

Java use Apache POI Export-note front-end do not use AJAX asynchronous request, if you want to eject the file download box, do not use asynchronous download. apahce POI POM Configuration

<!--Excel Import Export-->
		<dependency>
			<groupId>org.apache.poi</groupId>
			< artifactid>poi</artifactid>
			<version>3.9</version>
		</dependency>

		< dependency>
			<groupId>org.apache.poi</groupId>
			<artifactid>poi-ooxml</ artifactid>
			<version>3.9</version>
		</dependency>

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.9</version>
		</dependency>


Exoportexcelutil

Package com.boonya.common.utils.excel;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import Java.util.Date;
Import java.util.List;
Import Java.util.Map;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.poi.hssf.usermodel.HSSFCell;
Import Org.apache.poi.hssf.usermodel.HSSFCellStyle;
Import org.apache.poi.hssf.usermodel.HSSFRichTextString;
Import Org.apache.poi.hssf.usermodel.HSSFRow;
Import Org.apache.poi.hssf.usermodel.HSSFSheet;
Import Org.apache.poi.hssf.usermodel.HSSFWorkbook;
Import org.apache.poi.hssf.util.CellRangeAddress;
Import Org.apache.poi.xssf.usermodel.XSSFCell;
Import Org.apache.poi.xssf.usermodel.XSSFCellStyle;
Import org.apache.poi.xssf.usermodel.XSSFRichTextString;
Import Org.apache.poi.xssf.usermodel.XSSFRow;
Import Org.apache.poi.xssf.usermodel.XSSFSheet; ImpORT Org.apache.poi.xssf.usermodel.XSSFWorkbook;

Import Com.cvnavi.common.utils.DateUtil; @SuppressWarnings ("deprecation") public class Exportexcelutil {public static String GetFileName () {return dateutil.t
	Ostring (New Date (), "Yyyymmdd-hhmmss"); public static Xssfworkbook Getworkbook (list<?> resultlist, string[] showname, string[] Resourcefield, CLASS&L t;? > Resultobj, map<string, map<string, string>> FormatMap) throws SecurityException, NoSuchMethodExceptio N, IllegalArgumentException, illegalaccessexception, invocationtargetexception {xssfworkbook workbook = new XSSFWorkbo
		Ok ();
		Xssfsheet sheet = workbook.createsheet ("Sheet1");
		Sheet.setdefaultcolumnwidth ((short) 20); Xssfcellstyle Centerstyle = Workbook.createcellstyle ();//set to center horizontally centerstyle.setalignment (xssfcellstyle.align_
		CENTER);
		Centerstyle.setverticalalignment (Xssfcellstyle.vertical_center);
		Xssfrow Row;
		Xssfcell cell;
		Createtitle (showname, sheet); The following is the output of each row of the data below the output of theThe data below is for the output lines for (int i = 0, Len = resultlist.size (); i < Len; i++) {Object result = Resultlist.get (i);
			row = Sheet.createrow (i + 1); Create the i+1 line for (int j = 0; J < Resourcefield.length + +) {cell = Row.createcell (j);//Create the J column method met
				Hod
				method = Resultobj.getmethod (Resourcefield[j]);
				Here the reflection mechanism is used, where the reflection mechanism is used, where the reflection mechanism is used to get the result object of the corresponding method returned objects obj = Method.invoke (results); if (obj!= null) {if (FormatMap!= null && formatmap.containskey (Resourcefield)) {Cell.setcellvalue (f
					Ormatmap.get (Resourcefield). Get (Obj.tostring ()));
					else {Cell.setcellvalue (obj.tostring ());
	}}} return workbook; /** * * @Title: GetWorkbook2 @Description: TODO (Create Hssfworkbook) @param * resultlist @param showname @param reso Urcefield @param resultobj @param * formatmap @return @throws securityexception @throws * nosuchmethodexception @throw S illegalargumentexception @throws * ILLEGALACCESSEXCEPtion @throws invocationtargetexception Set file @return * Hssfworkbook return type @author: Pengjl @date June 27, 2017 afternoon 3:22:51 @thro WS */public static Hssfworkbook GetWorkbook2 (list<?> resultlist, string[] showname, string[] Resourcefield, C Lass<?> resultobj, map<string, map<string, string>> FormatMap) throws SecurityException, NoSuchMetho Dexception, IllegalArgumentException, Illegalaccessexception, invocationtargetexception {HSSFWorkbook workbook = new H
		Ssfworkbook ();
		Hssfsheet sheet = workbook.createsheet ("Sheet1");
		Sheet.setdefaultcolumnwidth ((short) 20); Hssfcellstyle Centerstyle = Workbook.createcellstyle ();//set to center horizontally centerstyle.setalignment (hssfcellstyle.align_
		CENTER);
		Centerstyle.setverticalalignment (Hssfcellstyle.vertical_center);
		Hssfrow Row;
		Hssfcell cell;
		CreateTitle2 (showname, sheet); 
			The following is the output of each row of data below is the output of the rows for the (int i = 0; i < resultlist.size (); i++) {Object result = Resultlist.get (i); row = Sheet.createroW (i + 1); Create the i+1 line for (int j = 0; J < Resourcefield.length + +) {cell = Row.createcell (j);//Create the J column method met
				Hod
				method = Resultobj.getmethod (Resourcefield[j]);
				Here the reflection mechanism is used, where the reflection mechanism is used, where the reflection mechanism is used to get the result object of the corresponding method returned objects obj = Method.invoke (results); if (obj!= null) {if (FormatMap!= null && formatmap.containskey (Resourcefield)) {Cell.setcellvalue (f
					Ormatmap.get (Resourcefield). Get (Obj.tostring ()));
					else {Cell.setcellvalue (obj.tostring ());
	}}} return workbook;  /** * @Title: CreateTitle2 @Description: TODO (Multiline header) @param showname @param * Sheet set file @return void return type @author: PENGJL @date June 27, 2017 * PM 3:23:30 @throws/private static void CreateTitle2 (string[) showname, Hssfsheet sheet)
		{Hssfrow row = sheet.createrow (0);//Create line 1th, that is, the output header creates the first Hssfcell cell;
			for (int i = 0; i < showname.length i++) {cell = Row.createcell (i); Create column I to create the first Cell.setcellvalUE (New hssfrichtextstring (Showname[i])); } private static void Createtitle (string[] showname, Xssfsheet sheet) {xssfrow row = sheet.createrow (0);//Create 1th
		Row, that is, the output table header creates the Xssfcell cell;
			for (int i = 0; i < showname.length i++) {cell = Row.createcell (i);
		Create column I to create the first cell.setcellvalue (new xssfrichtextstring (showname[i)); }/** * @Title: Createworkbook @Description: TODO (Create Hssfworkbook) @param * resultlist @param showname @return Settings Pieces @return Hssfworkbook * return type @author: Pengjl @date June 27, 2017 afternoon 3:23:41 @throws/public static Hssfworkbook Create
		Workbook (list<list<cell>> resultlist, string[] showname) {Hssfworkbook workbook = new HSSFWorkbook ();
		Hssfsheet sheet = workbook.createsheet ("Sheet1"); Hssfcellstyle Centerstyle = Workbook.createcellstyle ();//set to center horizontally centerstyle.setalignment (hssfcellstyle.align_
		CENTER);
		Centerstyle.setverticalalignment (Hssfcellstyle.vertical_center);
		CreateTitle2 (showname, sheet); Hssfrowrow = null;
		Hssfcell cell = null;
		Int[][] Arrasort;
		if (resultlist.size () = = 0) {Arrasort = new int[0][0];
		else {arrasort = new Int[resultlist.get (0). Size ()][resultlist.size ()];
			for (int i = 0; i < resultlist.size (); i++) {row = Sheet.createrow (i + 1);
			Sheet.setcolumnwidth (i + 1, 15);
			list<cell> celllist = Resultlist.get (i); for (int j = 0; J < Celllist.size (); j + +) {cell = Row.createcell (j);//Create Column J Cell.setcellvalue (Celllist.get (
				j). GetValue ());
				int b = Cell.getstringcellvalue (). GetBytes (). length;
				Arrasort[j][i] = b;
				if (Celllist.get (j). GetStyle ()!= null) {Cell.setcellstyle (Celllist.get (j). GetStyle ());
		The maximum column width (excluding headers) of}//column int widthinfo[] = Twomaxinfo (arrasort);
			With the title in the comparison column width for (int i = 0; i < showname.length i++) {//Sheet.autosizecolumn (i); Calculate the column (including the maximum width of the caption) int maxwidthinfo = Showname[i].getbytes (). length > Widthinfo[i]? Showname[i].getbytes (). Length:widthiNfo[i];
		Sheet.setcolumnwidth (i, maxwidthinfo * 256);
	return workbook;
		public static int[] Twomaxinfo (int[][] arrasort) {int[] arraysortinfo = null;
		Arraysortinfo = new Int[arrasort.length];
		int count = 0;
			For (int[] is:arrasort) {int[] Arrainfo = is;
			Arrays.sort (Arrainfo);
			Arraysortinfo[count] = arrainfo[arrainfo.length-1];
		count++;
	return arraysortinfo; /** * @Title: Createworkbookall @Description: TODO (Create Hssfworkbook) @param * vMap @param showname @return settings file @ret Urn Hssfworkbook return type @author: * PENGJL @date June 27, 2017 afternoon 3:20:04 @throws * * public static Hssfworkbook CREATEWORKBO Okall (map<string, list<list<cell>>> VMap, string[] showname) {Hssfworkbook workbook = new HSSFWorkboo
		K (); For (map.entry<string, list<list<cell>>> entry:vMap.entrySet ()) {Hssfsheet sheet = workbook.create
			Sheet (Entry.getkey ());
			Sheet.setdefaultcolumnwidth ((short) 15); Hssfcellstyle Centerstyle = WorKbook.createcellstyle ();//set to Horizontal center centerstyle.setalignment (hssfcellstyle.align_center);
			Centerstyle.setverticalalignment (Hssfcellstyle.vertical_center);
			CreateTitle2 (showname, sheet);
			Hssfrow Row;
			Hssfcell cell;
				for (int i = 0; i < Entry.getvalue (). Size (); i++) {row = Sheet.createrow (i + 1);
				list<cell> celllist = Entry.getvalue (). get (i); for (int j = 0; J < Celllist.size (); j + +) {cell = Row.createcell (j);//Create Column J Cell.setcellvalue (celllist.ge
					T (j). GetValue ());
					if (Celllist.get (j). GetStyle ()!= null) {Cell.setcellstyle (Celllist.get (j). GetStyle ());
			for (int i = 0; i < showname.length; i++) {sheet.autosizecolumn (i);
	} return workbook;  /** * @Title: Workbook2inputstream @Description: TODO (export Excel file) @param * Workbook @param fileName @param response
	@return @throws Exception * settings file @return InputStream return type @author: Pengjl @date June 27, 2017 * Afternoon 3:20:21 @throws * * Public Static inputstream Workbook2inputstream (Hssfworkbook workbook, String fileName, httpservletresponse response) throws Exce
		ption {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
		Workbook.write (BAOs);
		Baos.flush ();
		byte[] AA = Baos.tobytearray ();
		InputStream Excelstream = new Bytearrayinputstream (AA, 0, aa.length);
		Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8");
		Response.setheader ("Content-disposition", "attachment;filename=" + filename + ". xls");
		Response.getoutputstream (). write (AA);
		Response.setcontentlength (aa.length);
		Response.getoutputstream (). Flush ();
		Baos.close ();

	return excelstream; /** * * @Title: Workbook2inputstream @Description: TODO (export Excel file) @param * Workbook @param fileName @param res
	 Ponse @return @throws Exception * Set file @return InputStream return type @author: Pengjl @date June 27, 2017 * Afternoon 3:20:49 @throws */public static InputStream Workbook2inputstream (Xssfworkbook workbook, String FileName, HTTPSERVLETREsponse response) throws Exception {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
		Workbook.write (BAOs);
		Baos.flush ();
		byte[] AA = Baos.tobytearray ();
		InputStream Excelstream = new Bytearrayinputstream (AA, 0, aa.length);
		Response.setcontenttype ("Application/vnd.ms-excel;charset=utf-8");
		Response.setheader ("Content-disposition", "attachment;filename=" + filename + ". xlsx");
		Response.getoutputstream (). write (AA);
		Response.setcontentlength (aa.length);
		Response.getoutputstream (). Flush ();
		Baos.close ();

	return excelstream; /** * @Title: Createworkbookvarietyparam @Description: * TODO (Create Hssfworkbook) @param resultlist @param showname @p Aram * Headername @return Set file @return hssfworkbook return type @author: Pengjl @date * June 27, 2017 pm 3:21:22 @throws */PU Blic static Hssfworkbook Createworkbookvarietyparam (arraylist<arraylist<string>> resultList, String[) ShowName, arraylist<string> headername) {Hssfworkbook workbook = NEW Hssfworkbook ();
		Hssfsheet sheet = workbook.createsheet ("Sheet1");
		Sheet.setdefaultcolumnwidth ((short) 15); Hssfcellstyle Centerstyle = Workbook.createcellstyle ();//set to center horizontally centerstyle.setalignment (hssfcellstyle.align_
		CENTER);
		Centerstyle.setverticalalignment (Hssfcellstyle.vertical_center);
		/** * Set the style of the header * * Hssfcellstyle Titylstyle = Workbook.createcellstyle ();
		Createtitlevariety (ShowName, Headername, sheet, titylstyle);
		Hssfrow Row;
		Hssfcell cell; if (resultlist!= null && resultlist.size () > 0) {for (int i = 0; i < resultlist.size (); i++) {Arra
				ylist<string> rowresultlist = Resultlist.get (i); if (headername!= null && headername.size () > 0) {row = Sheet.createrow (short) (i + 1 + headername.size (
				)));
				else {row = Sheet.createrow (short) (i + 1)); } if (rowresultlist!= null && rowresultlist.size () > 0) {for (int n = 0; n <= rowresultlist.size (); n++) {cell = ROw.createcell (n);//Create Column J Cell.setcellstyle (Centerstyle);
						if (n = = 0) {//The first column of the Excel table is numbered, the header is: ordinal; eg:1,2,3,4 ... cell.setcellvalue (i + 1);
						else if (Rowresultlist.get (n-1)!= null) {Cell.setcellvalue (rowresultlist.get). toString ());
						else {cell.setcellvalue ("");
	}}} return workbook; /** * @Title: createtitlevariety @Description: TODO (Multiline header) @param * showname @param headername @param sheet @param Titylstyle Set File @return * void return type @author: Pengjl @date June 27, 2017 afternoon 3:24:24 @throws/private static void Createt Itlevariety (string[] showname, arraylist<string> headername, Hssfsheet sheet, Hssfcellstyle titylStyle) {HSSFR
		ow row;
		Hssfcell cell;
		Titylstyle.setalignment (Hssfcellstyle.align_center);
		Titylstyle.setverticalalignment (Hssfcellstyle.vertical_center); if (headername!= null && headername.size () > 0) {for (int i = 0; i < headername.size (); I+ +) {row = Sheet.createrow ((short) i);
					if (i = = 0) {cell = Row.createcell (i);
					Sheet.addmergedregion (New cellrangeaddress (I, I, (short) 0, (short) showname.length));
					Cell.setcellstyle (Titylstyle);
					if (Headername.get (i)!= null) {Cell.setcellvalue (New hssfrichtextstring (Headername.get (i). toString ()));
					else {cell.setcellvalue (new hssfrichtextstring (""));
					} else {cell = Row.createcell (i-1);
					Sheet.addmergedregion (New cellrangeaddress (I, I, (short) 0, (short) showname.length));
					if (Headername.get (i)!= null) {Cell.setcellvalue (New hssfrichtextstring (Headername.get (i). toString ()));
					else {cell.setcellvalue (new hssfrichtextstring ("")); }}//Set Excel field if (headername!= null && headername.size () > 0) {row = Sheet.createrow (
		Short) headername.size ());
		else {row = Sheet.createrow (0); for (int n = 0; n <= showname.length; n++) {if (n = = 0) {
				Cell = Row.createcell (n);
				Cell.setcellstyle (Titylstyle);
			Cell.setcellvalue (New hssfrichtextstring ("serial number"));
				else {cell = Row.createcell (n);
				Cell.setcellstyle (Titylstyle);
			Cell.setcellvalue (New hssfrichtextstring (showname[n-1));
 }
		}
	}
}

How to use

/** * @Title: Export * @Description: TODO (bicycle export && Export front-end Ajax request does not eject the download file) * @param request * @param response * @par Am Temperaturebean * @return settings file * @return String return type * @author: PENGJL * @date June 22, 2017 afternoon 8:38:43 * @throw S/@RequestMapping ("/export") public void Export (HttpServletRequest request,httpservletresponse Response,temperatur
        Ebean temperaturebean) {int maptype = Integer.parseint (Request.getparameter ("Maptype"));
            try {list<temperatureview> viewlist= itemperatureservice.querytrack (Temperaturebean, mapType,true);
            String[] ShowName = {"License plate number", "GPS Time", "Speed (km/hour)", "Elevation (m)", "position", "Temperature"};
            list<list<cell>> dataList = new arraylist<list<cell>> ();
            list<cell> celllist = new arraylist<cell> (); if (Viewlist.size () >0) {for (Temperatureview view:viewlist) {celllist = new ARRAYLIST&L T
	                Cell> (); Celllist.Add (New Cell (View.gettemperaturelist (). Get (0). Getplatecode ()));
	                Celllist.add (New Cell (View.getgpstime ()));
	                Celllist.add (New Cell (Double.parsedouble (View.gettemperaturelist (). Get (0). GetSpeed () + "")/10 + ""));
	                Celllist.add (New Cell (View.gettemperaturelist (). Get (0). Gethigh () + ""));
	                Celllist.add (New Cell (View.gettemperaturelist (). Get (0). GetLocation ()));
	                String temp = ""; For (Temperaturebean bean:view.getTemperatureList ()) {temp + = Bean.getappendname () + ":" + bean.gettemp
	                Erature () + bean.getunit () + ",";
	                } if (!temp.equals ("")) temp = temp.substring (0,temp.length ()-1);
	                Celllist.add (new Cell (temp));
	            Datalist.add (celllist);
            } String FileName = Exportexcel.getfilename (); Exportexcel.workbook2inputstream (Exportexcel.createworkbook (DataliSt, ShowName), filename,response);
        catch (Exception e) {e.printstacktrace (); }
	}

Test URL

Enter the export address in the browser: http://127.0.0.1:8081/cvnavi-monitoryt/temperature/export.do?tokenStr= a2e4ce20dbc8a4edac0ec5b2ad25d022&starttime=2017-06-27%2000:00:00&endtime=2017-06-27%2023:59:59& platecode=%e6%b2%aaawg102&maptype=2&vehicleid=4427355843467897


Direct access can be downloaded, so it is speculated that the front-end is not exported because it uses AJAX, the file itself is asynchronous, so the browser does not eject the download box.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.