天天看点

java操作excel之jxls导出excel模板数据

转载自。 https://blog.csdn.net/tomcat_2014/article/details/54928175

1.介绍

Jxls是一个小而易用的Java库, 它用于根据excel模板文件生成对应的excel数据文件.

使用Jxls只需要几行代码就可以建立非常复杂的excel报表, 我们需要做的工作室建立excel模板文件, 完成所需要的格式、公式、宏等,

然后写几行代码调用Jxls引擎解析excel模板文件并将数据作为参数输入到报表文件中.

2.语法

这个JEXL语法和JSTL语法十分相似.

<jx:forEach items="${list}" var="li">

${li.name}

</jx:forEach>

还可以求和

如$[SUM(F3)],求和F3这个单元格的所有值的和

3.依赖

  1. <dependency>
  2. <groupId>net.sf.jxls</groupId>
  3. <artifactId>jxls-core</artifactId>
  4. <version> .6</version>
  5. <scope>compile</scope>
  6. </dependency>

4.核心代码

读取项目中的excel模板:

  1. private Resource salaryExportResource;
  2. @PostConstruct
  3. public void setup() {
  4. salaryExportResource = new ClassPathResource( "/salaryTemplate.xls");
  5. }

渲染模板:

  1. @RequestMapping(value = "/export")
  2. public void exportSalaryTemplet(@ModelAttribute("form") SalaryCriteria form,
  3. HttpServletResponse response) throws Exception {
  4. //日期转化对象
  5. SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd");
  6. SimpleDateFormat timeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
  7. List<SalaryView> salaryList = salaryService.findSalaryList(form)
  8. .stream().map(salaryViewTransformer::transform)
  9. .collect(Collectors.toList());
  10. Map<String, Object> data = new HashMap<>();
  11. data.put( "dateFormat", dateFormat);
  12. data.put( "timeFormat", timeFormat);
  13. data.put( "printTime", new Date());
  14. data.put( "salaryList", salaryList);
  15. //将数据渲染到excel模板上
  16. Workbook workbook = new XLSTransformer().transformXLS(salaryExportResource.getInputStream(), data);
  17. ByteArrayOutputStream output = new ByteArrayOutputStream();
  18. workbook.write(output);
  19. String filename = "员工薪资单.xls";
  20. response.setContentType(String.format( "%s;charset=utf-8", "application/x"));
  21. response.setHeader( "Content-Disposition", "attachment;filename=" +
  22. new String(filename.getBytes( "utf-8"), "iso8859-1"));
  23. response.setHeader( "Content-Length", String.valueOf(output.toByteArray().length));
  24. // Streams.write(output.toByteArray(), response.getOutputStream());
  25. response.getOutputStream().write(output.toByteArray());
  26. }

       这里我们自己处理了Response,没必要交给spring的视图解析器.在返回响应前我们设置了响应的Header和ContentType以便客户端的浏览器解析为弹出下载.这里调用了transformer.transformXLS(in, beans)方法得到一个Workbook,这方法会把模板(至于模板怎么写,详细看官方文档)先读入到输入流再处理,再把Workbook的内容写入到输出流发送出去.

5.excel模板

java操作excel之jxls导出excel模板数据

6.最终效果

java操作excel之jxls导出excel模板数据