SpringMvc导出Excel实例代码

2025-05-29 0 36

前言

相信很多朋友在实际工作中都会要将数据导出成Excel的需求,通常这样的做法有两种。

一是采用JXL来生成Excel,之后保存到服务器,然后在生成页面之后下载该文件。

二是使用POI来生成Excel,之后使用Stream的方式输出到前台直接下载(ps:当然也可以生成到服务器中再下载。)。这里我们讨论第二种。

Struts2的方式

通常我会将已经生成好的HSSFWorkbook放到一个InputStream中,然后再到xml配置文件中将返回结果更改为stream的方式。如下:

?

1

2

3

4

5

6

7

8
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();

}

配置文件:

?

1

2

3

4

5

6

7
<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>

这样即可达到点击链接即可直接下载文件的目的。

SpringMVC的方式

先贴代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
@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();

}

}

其实springMVC和Struts2的原理上是一样的,只是Struts2是才去配置文件的方式。首先是使用createExcel()这个方法来生成Excel并返回,最后利用response即可向前台输出Excel,这种方法是通用的,也可以试用与Servlet、Struts2等。我们只需要在response的头信息中设置相应的输出信息即可。

总结

不管是使用Struts2,还是使用SpringMVC究其根本都是使用的response,所以只要我们把response理解透了不管是下载图片、world、Excel还是其他什么文件都是一样的。

GitHub地址:https://github.com/crossoverJie

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.jianshu.com/p/9f57cb7ab6ae#

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringMvc导出Excel实例代码 https://www.kuaiidc.com/119394.html

相关文章

发表评论
暂无评论