Jxls是一个小而易用的java库, 它用于根据Excel模板文件生成对应的excel数据文件.
使用Jxls只需要几行代码就可以建立非常复杂的excel报表, 我们需要做的工作室建立excel模板文件, 完成所需要的格式、公式、宏等,
然后写几行代码调用Jxls引擎解析excel模板文件并将数据作为参数输入到报表文件中.
这个JEXL语法和JSTL语法十分相似.
<jx:forEach items="${list}" var="li">
${li.name}
</jx:forEach>
还可以求和
如$[SUM(F3)],求和F3这个单元格的所有值的和
<dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.6</version> <scope>compile</scope> </dependency>4.核心代码
读取项目中的excel模板:
PRivate Resource salaryExportResource; @PostConstruct public void setup() { salaryExportResource = new ClassPathResource("/salaryTemplate.xls"); }渲染模板:@RequestMapping(value = "/export") public void exportSalaryTemplet(@ModelAttribute("form") SalaryCriteria form, HttpServletResponse response) throws Exception { //日期转化对象 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); List<SalaryView> salaryList = salaryService.findSalaryList(form) .stream().map(salaryViewTransformer::transform) .collect(Collectors.toList()); Map<String, Object> data = new HashMap<>(); data.put("dateFormat", dateFormat); data.put("timeFormat", timeFormat); data.put("printTime", new Date()); data.put("salaryList", salaryList); //将数据渲染到excel模板上 Workbook workbook = new XLSTransformer().transformXLS(salaryExportResource.getInputStream(), data); ByteArrayOutputStream output = new ByteArrayOutputStream(); workbook.write(output); String filename = "员工薪资单.xls"; response.setContentType(String.format("%s;charset=utf-8", "application/x")); response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"), "iso8859-1")); response.setHeader("Content-Length", String.valueOf(output.toByteArray().length)); // Streams.write(output.toByteArray(), response.getOutputStream()); response.getOutputStream().write(output.toByteArray()); }这里我们自己处理了Response,没必要交给spring的视图解析器.在返回响应前我们设置了响应的Header和ContentType以便客户端的浏览器解析为弹出下载.这里调用了transformer.transformXLS(in, beans)方法得到一个Workbook,这方法会把模板(至于模板怎么写,详细看官方文档)先读入到输入流再处理,再把Workbook的内容写入到输出流发送出去.
5.excel模板
6.最终效果
新闻热点
疑难解答