需求: 选择不同的时间段从数据库中获取报表文件的数据,生成对应的多个excel,然后把这些excel压缩打包下载下来。
过程大致如下面三幅图所示:
jxls官方英文教程
1、导入依赖
<!--excel生成工具-->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>1.0.9</version>
</dependency>
2、编写JxlsUtil,jxls的工具类
public class JxlsUtils {
static {
//添加自定义指令(可覆盖jxls原指令)
XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class); //合并单元格命令
}
public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> 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<String, Object> funcs = new HashMap<String, Object>();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
//必须要这个,否者表格函数统计会错乱
jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
}
}
public static void exportExcel(String templatePath, OutputStream os, Map<String, Object> 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 "";
}
在excel可以通过上文定义的utils去使用这个方法
3、定义excel模板
我把模板放在了resources的templates/xls/文件夹下
//遍历List的批注
jx:each(items="detailList" var="detail" lastCell="G6")
//jxls扫码范围的批注
jx:area(lastCell="H18")
excel模板说明
excel表对应java代码
最终效果
4、调用接口生成的excel代码
取出数据生成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<String,Object> 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();
}
}
5、调用接口生成多个excel,并且打包下载
@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<PurchaseOrderDto> 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<String, Object> 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 "下载成功";
}
调用此接口就会生成多个excel表的数据流然后打包下载
6、vue端请求下载excel压缩包的代码
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)
点击下载按钮
7、excel动态合并单元格
//合并代码
jx:merge(rows="detailList.size()" lastCell="A4")
8、excel插入序号的方式
可以在List的每一项中加入下标然后再取出来展示
或者可以通过此单元格自增实现序号功能
来源:CSDN
作者:k55
链接:https://blog.csdn.net/k393393/article/details/103608783