Springmvc exporting Excel (POI)

Source: Internet
Author: User

/** * Export Excel Table */@RequestMapping (value = "/doexportdata", method = {requestmethod.post, requestmethod.get }) public void Doexportuserdata (HttpServletRequest request, HttpServletResponse Response,modelmap modelmap) {Str              ing enddate = (String) request.getparameter ("EndDate");            Query data list list<user> userlist = Aservice.findbydate (EndDate);          Generate prompt information, response.setcontenttype ("application/vnd.ms-excel"); try{//Patchwork file name: Time + random number
String fileName = ""; string[] Date2 = Enddate.split ("-"); for (int i=0;i<date2.length;i++) {fileName = Filename+date2[i]; }
Method Two:
         String fileName = Enddate.replace ("-", "" "); FileName = Filename+math.round (Math.random () *10000);//Add random number Response.setheader ("Content-disposition", "Attachme Nt;filename= "+ filename +". xls "); Generate Workbook object Hssfworkbook workbook = new Hssfworkbook (); Generate Sheet Object Hssfsheet sheet = workbook.createsheet ("user list"); Set sheet page name Hssfrow row = sheet.createrow (0); Hssfcellstyle style = Workbook.createcellstyle (); Style.setalignment (Cellstyle.align_center); Create a center format Hssfcell cell = Row.createcell (0); Cell.setcellvalue ("department name"); Cell.setcellstyle (style); Cell = Row.createcell (1); Cell.setcellvalue ("work number"); Cell.setcellstyle (style); Cell = Row.createcell (2); Cell.setcellvalue ("name"); Cell.setcellstyle (style); Cell = Row.createcell (3); Cell.setcellvAlue ("Time"); Cell.setcellstyle (style); Cyclic data for (int i = 0; i < userlist.size (); i++) {row = Sheet.createrow (i + 1); User user = Userlist.get (i); Create a cell and set the value Row.createcell (0). Setcellvalue (User.getdeptname ()); Row.createcell (1). Setcellvalue (User.getuserid ()); Row.createcell (2). Setcellvalue (User.getname ()); Row.createcell (3). Setcellvalue (EndDate); }//File export path, exportfile file in Project under String Path = Request.getsession (). Getservletcontext () . Getrealpath ("/"); String filePath =path+ "exportfile\\" +filename+ ". xls"; OutputStream OS = new FileOutputStream (FilePath); Workbook.write (OS); Os.close (); Download the file (just export to the appropriate file below, download does not, do not add this method, in Google Browser can not directly open the file, prompt to save the file name is inconsistent, open is empty) file TemplateFile = new file (FilePath); Fileutil.downloadfile (response, templatefile); }catch (Exception e) {e.printstacktrace (); } }

Fileutil.java Download related tool classes

Import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;import Javax.servlet.http.httpservletresponse;import org.apache.commons.lang3.stringutils;/** * File Tools Class */public class fileutil {/** * Download file * * @param response * @param file * @throws Exception */public static void DownloadFile (HTTPSERVLETR Esponse response, File file) throws Exception {if (null = = Response | | null = = File) Return;inputstream is = Null;outputstre Am OS = null;if (File.exists ()) {//2 file name string filename = Getfilenamebycompletefilepath (File.getname ());//3 File size string Filelength = string.valueof (File.length ());//4 Download file name string realdownloadfilename = new String (Filename.getbytes (), " 8859_1 ");//5 Set response parameter Response.reset (); Response.setcontenttype (" application/x-msdownload; "); Response.setheader ("Content-disposition", "attachment; Filename= "+ realdownloadfilename); Response.setheader("Content-length", filelength); Response.setheader ("Cache-control", "Must-revalidate, Post-check=0, pre-check=0"); Response.setheader ("Pragma", "public"); Response.setdateheader ("Expires", System.currenttimemillis () + 1000L); try { is = new Bufferedinputstream (new FileInputStream), os = new Bufferedoutputstream (Response.getoutputstream ()); byte[] buffer = new Byte[1024];while (true) {int size = is.read (buffer, 0, 1024x768), if (size = =-1) {break;} Os.write (buffer, 0, size);}} catch (Exception e) {e.printstacktrace ();} finally {try {if (is! = null) {Is.close ();}} catch (IOException e) {E.printstac Ktrace ();} try {if (OS! = null) {Os.close ()}} catch (IOException e) {e.printstacktrace ();}} Response.setstatus (HTTPSERVLETRESPONSE.SC_OK); try {response.flushbuffer ();} catch (IOException e) {}} else {// System.out.println ("Download file does not exist, file path:" + File.getabsolutepath ());//If the file does not exist, create an exception object and throw the throw new Exception ();}} public static string Getfilenamebycompletefilepath (string path) {if (Stringutils.isblank (path)Return "";//1 The conversion path is local string path = Tolocalpath (path);//2 Handles if (Stringutils.isnotblank (path)) {int index = Path.lastindexof (Fi le.separator); return path = path.substring (index + 1);} Return "";} public static final String Tolocalpath (string pathstring) {if (Stringutils.isblank (pathstring)) return "";p athstring = Replace (pathstring, "/", file.separator);p athstring = replace (pathstring, "\ \", file.separator); return pathstring;} public static final string replace (string line, String oldstring,string newstring) {//recursive algorithm int i = 0;if ((i = Line.indexof (oldstring, I)) >= 0) {char[] line2 = Line.tochararray (); char[] newString2 = Newstring.tochararray (); int olength = Oldstring.length ();  StringBuffer buf = new StringBuffer (line2.length), Buf.append (line2, 0, I). Append (newString2); i + = olength;int j = I;while ((i = Line.indexof (oldstring, i)) > 0) {Buf.append (line2, J, I-j). Append (newString2); i + = Olength;j = i;} Buf.append (Line2, J, Line2.length-j); return buf.tostring ();} return line;}}

  

Springmvc exporting Excel (POI)

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.