通过jquery下载后端传过来的文件
1️⃣ 后端
后端导过来的文件是二进制流(blob)格式,所以前端需要用blob的格式接一下这个文件
2️⃣ 前端
3️⃣ 代码
// 表头
List<List<String>> listHead = new ArrayList<>();
@RequestMapping(value = "/exportTable", method = {RequestMethod.POST, RequestMethod.GET}) public void export(HttpServletResponse response, @RequestParam Map<Object, Object> params) throws IOException { response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("UTF-8"); String fileName = URLEncoder.encode("test", "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); String tableName = params.get("table").toString(); EasyExcel.write(response.getOutputStream()) .registerConverter(new config()) .head(head1(tableName)).sheet("模板") .doWrite(data(tableName )); // 每次导出完清空listHead listHead.clear(); } public class config implements Converter<HashMap<String, Object>> { @Override public Class<HashMap> supportJavaTypeKey() { return HashMap.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } /** * 这里是写的时候会调用。/ */ @Override public WriteCellData<HashMap<String, Object>> convertToExcelData(WriteConverterContext<HashMap<String, Object>> context) { return new WriteCellData<HashMap<String, Object>>(String.valueOf(context.getValue())); } } private List<List<String>> head1(String tableName) { return listHead; } private List<List<Object>> data(String tableName) { // 表格的动态表头 List<String> head = new ArrayList<>(); // 表格内的数据 List<Map<String, Object>> dataHead = exportYxService.findAllMap(tableName); List<List<Object>> list = new ArrayList<>(); Map<String, Object> mapData = new HashMap<>(); // 取出表头 for (int i = 0; i < dataHead.size(); i++) { mapData = dataHead.get(0); } for (String key : mapData.keySet()) { head.add(key); } for (Map<String, Object> map : dataHead) { List<Object> list1 = new ArrayList<>(); for (String key : map.keySet()) { list1.add(map.get(key)); } list.add(list1); } for (String s : head) { listHead.add(Collections.singletonList(s)); } return list; } }
// 导出按钮方法
function Tablexport() {
$.ajax({
url: '../exportYxController/exportTable.json',
type: "POST",
data: {
'table': tableName
},
// 将前端返回的数据支持blob类型
xhr: function () {
let xhr = new XMLHttpRequest()
xhr.responseType = 'blob'
return xhr
},
responseType: 'blob',
success: function (res) {
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
let elink = document.createElement('a');
elink.download = "test";
elink.href = window.URL.createObjectURL(blob);
elink.style.display = 'none';
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
window.URL.revokeObjectURL(blob);
}
})
}