@PostMapping("/download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
ExcelWriterSheetBuilder sheet = EasyExcel.write(response.getOutputStream(), OneXlsDto.class)
.autoCloseStream(Boolean.FALSE).registerWriteHandler(horizontalCellStyleStrategy).sheet("独立值集导入模板").doWrite(data());
}
private List<OneXlsDto> data() {
List<OneXlsDto> list = ListUtils.newArrayList();
for (int i = 0; i < 10; i++) {
OneXlsDto data = new OneXlsDto();
data.setField1("字符串" + i);
list.add(data);
}
return list;
}
@Data
@HeadRowHeight(20)
@ColumnWidth(20)
public class OneXlsDto extends AeDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 值集名称
*/
@ExcelProperty(value="字段1")
private String field1;
@ExcelProperty(value="字段2")
private String field2;
@ExcelProperty(value="启用标识(Y/N)")
private String enabledFlag;
@ExcelProperty(value="起始日期")
@DateTimeFormat("yyyy-MM-dd")
@ContentStyle(dataFormat = 14)
private Date startDate;
@ExcelProperty(value = "失效日期")
@DateTimeFormat("yyyy-MM-dd")
@ContentStyle(dataFormat = 14)
private Date expirationDate;
}
【'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'】设置的
【responseType: 'blob'】
this.axios({
method: 'post',
url: '/urlPrefix/download',
responseType: 'blob'
}).then(function(res) {
let temp = res.headers['content-disposition']
.split(';')[1]
.split('filename=')[1] //从返回头取出文件名称
let fileNameStr = unescape(decodeURI(temp)) //中文文件名需解码
let fileName = fileNameStr.replace(/\"/g, '').replace(/\'/g, '')
let blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
var link = document.createElement('a')
document.body.appendChild(link)
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//释放内存
window.URL.revokeObjectURL(link.href)
document.body.removeChild(link)
}
})
转载地址:
基于SpringBoot-Vue-EasyExcel实现的Excel文件导出+导入_JasonZhang1416的博客-程序员宅基地 - 程序员宅基地