SpringMvc exports Excel instance code
- 2020-05-27 05:31:53
- OfStack
preface
It is believed that many of my friends will export the data into the requirements of Excel in their actual work. There are usually two ways to do this.
1 is to generate Excel using JXL, save it to the server, and then download the file after the page is generated.
POI is used to generate Excel, and then Stream is used to output to the foreground for direct download (ps: of course, it can also be generated to the server for download). . So let's talk about the second one.
Struts2 way
Usually I will put the generated HSSFWorkbook into one InputStream and then go to the xml configuration file and 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();
}
Profile:
<action name="exportXxx" class="xxxAction" 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>
You can click the link to download the file directly.
SpringMVC way
First paste the code:
@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, the principle of springMVC and Struts2 is the same, but Struts2 is the way to configure the file. The first is to use
createExcel()
This method generates Excel and returns it
response
You can output Excel to the front desk. This method is universal and can be tried out
Servlet、Struts2
And so on. We just need to be here
response
The corresponding output information can be set in the header information of.
conclusion
Whether we use Struts2 or SpringMVC, response is used at all, so as long as we understand response completely, whether we download pictures, world, Excel or other files, it is the same.
GitHub address: https: / / github com/crossoverJie