后端
@PostMapping("/export")
public void exportData(@ApiIgnore @RequestBody Map<String, Object> formData, HttpServletRequest request, HttpServletResponse response) throws IOException, DownloadException {
ArrayList<LinkedHashMap<String, Object>> exportFiled = new ArrayList<>();
if (formData.containsKey("exportFiled")) {
exportFiled = (ArrayList) formData.get("exportFiled");
formData.remove("exportFiled");
}
if (exportFiled.size() == 0) {
throw new DownloadException("最少选择一项导出字段");
}
List<RecordingBillEntity> list = service.queryList(formData);
HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("123");
int rowIndex = 0;
//region 列名
Row headerRow = sheet.createRow(rowIndex); //第一行,列头
CellStyle headStyle = workbook.createCellStyle(); //列头样式设置
headStyle.setAlignment(HorizontalAlignment.CENTER);
headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setBold(true);
headStyle.setFont(font);
int i = 0;
headerRow.createCell(i).setCellValue("序号");
headerRow.getCell(i).setCellStyle(headStyle);
sheet.setColumnWidth(i, 5 * 256);
i++;
for (LinkedHashMap<String, Object> filed : exportFiled) {
headerRow.createCell(i).setCellValue(MapUtils.getString(filed, "name"));
headerRow.getCell(i).setCellStyle(headStyle);
sheet.setColumnWidth(i, 18 * 256);
i++;
}
rowIndex++;
//endregion
//region 数据
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (RecordingBillEntity entity : list) {
CellStyle itemStyle = workbook.createCellStyle();
itemStyle.setVerticalAlignment(VerticalAlignment.CENTER);
itemStyle.setAlignment(HorizontalAlignment.LEFT);
Row itemRow = sheet.createRow(rowIndex);
itemRow.setHeightInPoints(25);
int ci = 0;
itemRow.createCell(ci).setCellValue(rowIndex + 1);
itemRow.getCell(ci).setCellStyle(itemStyle);
ci++;
for (LinkedHashMap<String, Object> filed : exportFiled) {
String filedCode = MapUtils.getString(filed, "value");
Cell cell = itemRow.createCell(ci);
cell.setCellStyle(itemStyle);
String v = "";
try {
Field f = entity.getClass().getDeclaredField(filedCode);
f.setAccessible(true);
Object value = f.get(entity);
if (f.getType().equals(Date.class)) {
v = sdf.format((Date) value);
} else {
v = String.valueOf(value);
}
ci++;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
cell.setCellValue(v);
}
rowIndex++;
}
//endregion
//region export
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/ms-word");
// response.setContentLength(att.getSize());
String filename = "123.xls";
//设置文件下载头
String agent = (String) request.getHeader("USER-AGENT");
if (agent != null && agent.indexOf("Firefox") != -1) {
String enableFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(filename.getBytes("UTF-8")))) + "?=";
response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
} else {
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
}
response.addHeader("Last-Modified", new Date().toString());
// response.addHeader("Content-Length", att.getSize() + "");
@Cleanup OutputStream os = response.getOutputStream();
workbook.write(os);
response.flushBuffer();
//endregion
}
前端调用
that.$http({
method: 'post',
url: "/export",
data: params,
responseType: 'blob',//服务器返回的数据类型
}).then((res) => {
// 处理返回的文件流
const blob = new Blob([res.data],{type: "application/vnd.ms-excel"});//,{type: 'application/vnd.ms-excel;charset=utf-8'}
let fileName = '123.xls';
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}).catch(err => {
console.log(err);
})
},