SpringMVC层:
@ApiOperation(value = "导出") @RequestMapping(value = "/export/queries", method = RequestMethod.GET) public void exportQueries(@RequestParam(required = false) String customerNo, @RequestParam(required = false) String projectNo, HttpServletRequest request, HttpServletResponse response) throws IOException { ProjectAccountVo projectAccountVo = new ProjectAccountVo(); projectAccountVo.setCustomerNo(customerNo); projectAccountVo.setProjectNo(projectNo); List<ProjectAccountVo> list = this.projectAccountService.queryForExport(projectAccountVo); Context context = new Context(); //导出数据 context.putVar("account", list); try { parseExcelService.exportExcel("projectAccount.xlsx", "account", context, request, response); } catch (IOException e) { throw new ApplicationException("导出失败"); } }
this.projectAccountService.queryForExport(projectAccountVo);这段代码是从数据库中查出你需要导出的数据.然后把数据存放到Context容器中
Service层代码:
/** * 导出Excel * * @param templateFileName 模板文件名称 * @param destFileName 生成文件名称 * @param context 内容 * @param request * @param response * @throws IOException */ public void exportExcel(String templateFileName, String destFileName, Context context, HttpServletRequest request, HttpServletResponse response) throws IOException { StringBuilder builder = new StringBuilder(); //获取文件,该文件就是导出的模板文件 templateFileName = builder.append(request.getServletContext().getRealPath("/")).append("/template/export/").append(templateFileName).toString(); builder.setLength(0); //生成文件名称 destFileName = builder.append(destFileName).append("-").append(DateUtil.format2String(new Date(), DateUtil.DATE_DIGIT_FULL)).toString(); response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(destFileName.getBytes("gbk"), "iso8859-1") + ".xlsx"); //http输出流 OutputStream out = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(templateFileName); //多sheet生成后需删除模块页,需调用processTemplateAtCell方法,正常调用processTemplate即可 JxlsHelper.getInstance().processTemplate(fileInputStream, out, context); fileInputStream.close(); out.close(); }
jx:each顾名思义就是遍历代码中放进context中的list,
context.putVar("account", list); items就是account;
jx:area是限制解析Excel的范围,值得注意的是这个jx:area这个标签必须放在A1这个位置,也就是左上角