handleExportXls(fileName) {
if (!fileName || typeof fileName != 'string') {
fileName = '导出文件'
}
let param = this.getQueryParams()
param.instanceId = this.instance.id
if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
param['selections'] = this.selectedRowKeys.join(',')
}
console.log('导出参数', param)
downFile(this.url.exportXlsUrl, param).then((data) => {
if (!data) {
this.$message.warning('文件下载失败')
return
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
} else {
let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + '.xls')
document.body.appendChild(link)
link.click()
document.body.removeChild(link) //下载完成移除元素
window.URL.revokeObjectURL(url) //释放掉blob对象
}
})
}
@RequestMapping(value = "/exportXls")
public void exportXls(HttpServletRequest request, HttpServletResponse response) {
try {
List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 = new HashMap<>();
map1.put("name","小明");
map1.put("age","21");
map1.put("degree","36");
map1.put("link_name","小八");
map1.put("link_age","33");
dataList.add(map1);
Map<String,Object> map2 = new HashMap<>();
map2.put("name","小王");
map2.put("age","24");
map2.put("degree","37");
map2.put("link_name","小六");
map2.put("link_age","26");
dataList.add(map2);
List<ExcelExportEntity> entityList = new ArrayList<>();
// 一般表头使用这种两个参数的构造器
ExcelExportEntity e1 = new ExcelExportEntity("姓名","name");
ExcelExportEntity e2 = new ExcelExportEntity("年龄","age");
ExcelExportEntity e3 = new ExcelExportEntity("体温","degree");
entityList.add(e1);
entityList.add(e2);
entityList.add(e3);
// 需要被设置成子表头的使用这种三个参数的构造器,设置colspan为true
ExcelExportEntity e5 = new ExcelExportEntity("姓名","link_name",true);
ExcelExportEntity e6 = new ExcelExportEntity("年龄","link_age", true);
entityList.add(e5);
entityList.add(e6);
// 合并表头也需要设置colspan为true
ExcelExportEntity e4 = new ExcelExportEntity("紧急联系人","linkman",true);
List<String> sub = new ArrayList<>();
sub.add("link_name");
sub.add("link_age");
// 还需要设置一个子表头key的集合
e4.setSubColumnList(sub);
entityList.add(e4);
ExcelExportEntity en = new ExcelExportEntity("总分", "total", 30);
entityList.add(en);
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "sheetName"),entityList,dataList);
// 重点,导出结果写入流中
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
总结:
- 需要注意把
Workbook
写入response
中