Preface
I believe that many friends will export data into Excel's requirements in actual work. There are usually two ways to do this.
First, use JXL to generate Excel, then save it to the server, and then download the file after the page is generated.
The second is to use POI to generate Excel, and then use Stream to output it to the front desk to download it directly (ps: of course, it can also be generated to the server and then downloaded.). Here we discuss the second type.
Struts2's way
Usually I would put the already generated HSSFWorkbook into an InputStream and then go to the xml configuration file to change the return result to stream. as follows:
private void responseData(HSSFWorkbook wb) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); baos.flush(); byte[] aa = baos.toByteArray(); excelStream = new ByteArrayInputStream(aa, 0, aa.length); baos.close();}Configuration file:
<action name="exportXxx" method="exportXxx"> <result name="exportSuccess" type="stream"> <param name="inputName">excelStream</param> <param name="contentType">application/vnd.ms-excel</param> <param name="contentDisposition">attachment;filename="Undefined.xls"</param> </result></action>
This will achieve the purpose of clicking on the link to download the file directly.
SpringMVC way
Post the code first:
@RequestMapping("/exportXxx.action")public void exportXxx(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="scheduleId", defaultValue="0")int scheduleId){ HSSFWorkbook wb = createExcel(scheduleId); try { response.setHeader("Content-Disposition", "attachment; filename=appointmentUser.xls"); response.setContentType("application/vnd.ms-excel; charset=utf-8") ; OutputStream out = response.getOutputStream() ; wb.write(out) ; out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } In fact, springMVC and Struts2 are the same in principle, but Struts2 is the way to configure the file. First, use createExcel() method to generate Excel and return it. Finally, use response to output Excel to the foreground. This method is general, and you can also try it with Servlet、Struts2 , etc. We only need to set the corresponding output information in response header information.
Summarize
Whether using Struts2 or SpringMVC, it is basically used response, so as long as we understand the response thoroughly, whether it is downloading pictures, world, Excel or other files, it is the same.
GitHub address: https://github.com/crossoverJie
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.