一、需求
页面有个 table,是综合统计计算而来的产物,现在想把它已 excel 的方式导出来,excel 有样式要求,为了图省事,导出的操作就放在后台逻辑来处理。
数据查询复杂,所以就直接将数据传递给后台,然后由后台封装再下载。
二、实现
起初想的是 ajax,但是否定了,因为 ajax 请求是不能够返回文件流的,由于有很大的数据做参数进行传递,所以就使用的讨巧的方式——form 表单提交。
原理就是生成一个临时的 form 表单,表单的提交是可以返回文件下载功能的。
如下贴代码:
<button type="button" class="btn btn-primary" onclick="exportComprehensiveTable()">导出</button>
// 导出表格信息
function exportComprehensiveTable(){
var comprehensiveTableData = $('#comprehensive_table').bootstrapTable('getData');
if (comprehensiveTableData.length > 0) {
$('.exportComprehensiveTableBtn').attr('disabled','disabled');
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","/customer/comprehensive/download");
var input1=$("<input>");
input1.attr("type","hidden");
input1.attr("name","exportData");
input1.attr("value",(JSON.stringify(comprehensiveTableData)));
$("body").append(form);//将表单放置在web中
form.append(input1);
form.submit();//表单提交
form.remove();
setTimeout(function () {
$('.exportComprehensiveTableBtn').removeAttr('disabled');
hideOverLay();
}, 1000);
}
}@PostMapping("/comprehensive/download")
public ResponseEntity<InputStreamResource> downloadComprehensive(@RequestParam(name = "exportData") Object data) {
String fileName = "综合统计.xlsx";
InputStream is = customerService.downloadComprehensive(JSON.parseObject(data.toString(), List.class));
if (is == null) return null;
HttpHeaders headers = new HttpHeaders();
try {
headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
headers.add("content-type", "application/octet-stream");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(is));
}

文章评论