SpringBoot+EasyExcel导出xlsx表
导出excel接口
EasyExcel官方文档:
https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write#since-2
因为我们是web中的一个项目,所以定位到这个位置
通过文档我们发现,我们只需要设置响应头和编码文件类型的一些设置,便可通过EasyExcel进行写数据。所以我们在web项目中,我们需要从数据库中获取需要的excel数据,并写入到excel中。如果报错了,就返回给前台报错信息即可。
抽取设置响应头的设置
/**
* 抽取EasyExcel的设置响应头
* @param response
* @param fileName
* @throws IOException
*/
public static void setDownloadHeader(HttpServletResponse response, String fileName) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fname = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fname);
}
excel列标题的header信息
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelCategoryVo {
//分类名
@ExcelProperty("分类名")
public String name;
//描述
@ExcelProperty("描述")
public String description;
//状态
@ExcelProperty("状态:0正常,1禁用")
private String status;
}
导出分类信息excel的接口
@GetMapping("/export")
public void export(HttpServletResponse response){
try {
//设置响应头的header
WebUtils.setDownloadHeader(response, "分类.xlsx");
//查询需要导出的信息
List<Category> categoryList = categoryService.list();
List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryList, ExcelCategoryVo.class);
//把查询分类的信息写入到excel中
EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class)
.autoCloseStream(Boolean.FALSE)
//工作簿的名称
.sheet("分类导出")
.doWrite(excelCategoryVos);
} catch (IOException e) {
e.printStackTrace();
//导出失败,返回前端错误信息
ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
WebUtils.renderString(response, JSON.toJSONString(responseResult));
}
}
这里需要明确两个地方,这里的第一个红框框是excel列标题的header信息的对象封装类,第二个红框框就是表格需要的数据。