结果
代码
private static final String EXPORT_CONTENT_TYPE = "application/vnd.ms-excel";
private static final String EXPORT_ENCODING = "UTF-8";
@PostMapping("/exportTest")
@ApiOperation("导出测试")
@RequiresPermissions("dashboard:export")
@TestApiEnv
public void exportTest(@Validated @RequestBody ExportTestRequest<ExportTestVo> request) {
Page<ExportTestVo> page = service.getList(request.cancelPage());
List<ExportTestExcel> vos = BeanUtils.copyBeans(page.getRecords(), ExportTestExcel::new);
ExcelUtil.exportData("222", ExportTestExcel.class, vos);
}
public static <T> void exportData(String name,Class<?> headClass,List<T> data){
exportDataNative(name, name, headClass, data);
}
private static <T> void exportDataNative(String excelName, String sheetName, Object head, List<T> data) {
Assert.notNull(head,()->new BusinessException("head不能为null"));
try {
excelName = URLEncoder.encode(excelName + ExcelTypeEnum.XLS.getValue(),EXPORT_ENCODING);
HttpServletResponse response = SpringUtils.getResponse();
response.setContentType(EXPORT_CONTENT_TYPE);
response.setCharacterEncoding(EXPORT_ENCODING);
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + excelName);
// 创建excel
ExcelWriterBuilder write = EasyExcelFactory.write(response.getOutputStream());
if(head instanceof List){
//noinspection unchecked
write.head((List<List<String>>) head);
}else if(head instanceof Class){
//noinspection rawtypes
Class<?> headClass = (Class) head;
write.head(headClass);
if(ExcelGroupMergeStrategy.contains(headClass,data.size())){
ExcelGroupMergeStrategy mergeStrategy = ExcelGroupMergeStrategy.generate(headClass,data.size());
write.registerWriteHandler(mergeStrategy);
}
}else {
log.error("exportDataNative() head类型不能为"+head.getClass().getName());
throw new BusinessException("不支持该head类型");
}
// 自适应列宽(不需要就忽略)
write.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.sheet(sheetName)
.doWrite(data);
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("下载报表异常");
}
}
修复
方式一
把EXPORT_CONTENT_TYPE
的值改成application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
把ExcelTypeEnum.XLS.getValue()
改成ExcelTypeEnum.XLSX.getValue()
方式二
controller导出方法参数列表里添加HttpServletResponse response参数
@PostMapping("/exportTest")
@ApiOperation("导出测试")
@RequiresPermissions("dashboard:export")
@TestApiEnv
public void exportTest(HttpServletResponse response,@Validated @RequestBody ExportTestRequest<ExportTestVo> request) {
提示
前后端
content-type
需要一致
后端使用application/vnd.ms-excel
前端也要使用application/vnd.ms-excel
后端使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
前端也要使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet