需求: 选择不同的时间段从数据库中获取报表文件的数据,生成对应的多个excel,然后把这些excel压缩打包下载下来。
过程大致如下面三幅图所示:
jxls官方英文教程
org.jxls
jxls
2.4.4
org.jxls
jxls-poi
1.0.14
org.jxls
jxls-jexcel
1.0.9
public class JxlsUtils {
static {
//添加自定义指令(可覆盖jxls原指令)
XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class); //合并单元格命令
}
public static void exportExcel(InputStream is, OutputStream os, Map model) throws IOException {
Context context = PoiTransformer.createInitialContext();
if (model != null) {
for (String key : model.keySet()) {
context.putVar(key, model.get(key));
}
}
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(is, os);
//获得配置
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
//设置静默模式,不报警告
//evaluator.getJexlEngine().setSilent(true);
//函数强制,自定义功能
Map funcs = new HashMap();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
//必须要这个,否者表格函数统计会错乱
jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
}
}
public static void exportExcel(String templatePath, OutputStream os, Map model) throws Exception {
File template = getTemplate(templatePath);
if (template != null) {
exportExcel(new FileInputStream(template), os, model);
} else {
throw new Exception("Excel 模板未找到。");
}
}
在JxlsUtil中写上excel要使用到方法(不要写成静态方法)
// 日期格式化
public String dateFmt(Date date, String fmt) {
return dateFmt(date, fmt, "");
}
// 日期格式化
public String dateFmt(Date date, String fmt, String defaultStr) {
if (date == null) {
return defaultStr;
}
try {
SimpleDateFormat dateFmt = new SimpleDateFormat(fmt);
return dateFmt.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
我把模板放在了resources的templates/xls/文件夹下
//遍历List的批注
jx:each(items="detailList" var="detail" lastCell="G6")
//jxls扫码范围的批注
jx:area(lastCell="H18")
取出数据生成excel
@GetMapping(value = "/export/purchase")
public void purchaseExport(HttpServletResponse response,String id) throws Exception {
try {
PurchaseOrderExportVo vo=new PurchaseOrderExportVo();
//Excel导出配置 获取resources下面的模板
String url = ResourceUtils.getURL("classpath:").getPath();
String config = url + "templates/xls/sell_accept.xlsx";
String fileName = "销售验收单";
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName+".xlsx", "UTF-8"));
response.setContentType("application/vnd.ms-excel");
Map map=new HashMap();
map.put("detailList",vo.getOrderList());
map.put("vo",vo);
try(InputStream is = new FileInputStream(config)) {
try (OutputStream os = response.getOutputStream()) {
//开始到处excel
JxlsUtils.exportExcel(config, os, map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping(value = "/export/purchaseOrders")
public String purchaseAcceptExports(HttpServletRequest request, HttpServletResponse response, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam String type) {
endTime = new Date(endTime.getTime() + 86400000L);
List purchaseOrderDtos = directionalService.getPurchaseOrderByTimes(startTime, endTime);
if (purchaseOrderDtos == null || purchaseOrderDtos.size() == 0) return "参数为空";
try (ServletOutputStream bos = response.getOutputStream();
//定义个zip输出流
ZipOutputStream zos = new ZipOutputStream(bos)) {
//Excel导出配置 获取resources下面的模板
String url = ResourceUtils.getURL("classpath:").getPath();
String config = url + "templates/xls/sell_accept.xlsx";
String fileName = "销售验收单";
//以zip压缩包方式响应
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
//循环输出多个文件
purchaseOrderDtos.stream().forEach(dto -> {
PurchaseOrderExportVo vo = new PurchaseOrderExportVo();
//中间逻辑过程 省略。。。。。。。。。。。。。。。。。。
Map map = new HashMap();
map.put("detailList", dto.getDetailList());
map.put("vo", vo);
try (InputStream is = new FileInputStream(config)) {
JxlsUtils.exportZipExcel(fileName + "_" + dto.getFileNo(), zos, is, map);
} catch (Exception e) {
}
});
//刷新zip输出流
zos.flush();
zos.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return "下载成功";
}
var elemIF = document.createElement('iframe')
elemIF.src = this.baseURL + this.CONSTAINT.getCenterUrl(this.title) + '?startTime=' + this.$moment(this.start_time).format('YYYY-MM-DD') + '&endTime=' +
this.$moment(this.end_time).format('YYYY-MM-DD') +
'&type=' + this.CONSTAINT.getTypp(this.title)
elemIF.style.display = 'none'
document.body.appendChild(elemIF)
//合并代码
jx:merge(rows="detailList.size()" lastCell="A4")