1、首先导入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2、编写工具类
public class XlxsTool {
// 使用指定类初始化日志对象,在日志输出的时候,可以打印出日志信息所在类
private static final Logger log = LoggerFactory.getLogger(XlxsTool.class);
// 导入Excel(支持导入单个sheet的Excel)
// clazz 泛型 T 的具体类对象
public static <T> List<T> loadExcel(InputStream inputStream, Class<T> clazz) {
ExcelDataListener<T> excelDataListener = new ExcelDataListener<>();
EasyExcel.read(inputStream, clazz, excelDataListener).sheet().doRead();
return excelDataListener.getResult();
}
// 导出Excel
//
public static <T> void export(HttpServletResponse response, List<T> dataList, String fileName, String sheetName, Class<T> clazz) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")+ ".xlsx"
+ ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8")+ ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build();
WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
excelWriter.write(dataList, writeSheet);
excelWriter.finish();
}
// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public static class ExcelDataListener<T> extends AnalysisEventListener<T> {
private final List<T> result = new ArrayList<>();
//这个每一条数据解析都会来调用
@Override
public void invoke(T data, AnalysisContext context) {
result.add(data);
}
//所有数据解析完成了 都会来调用
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
//获取数据的方法
public List<T> getResult() {
return result;
}
}
}
3、controller层调用
@PostMapping("/import")
public BaseResponse<String> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
List<User> dataList = XlxsTool.loadExcel(file.getInputStream(), User.class);
boolean b = userService.saveBatch(dataList);
return ResultUtils.success();
}
@GetMapping("/export")
public void exportExcel(HttpServletResponse response) throws IOException {
List<User> dataList =userService.list();// 获取需要导出的数据列表
XlxsTool.export(response,dataList,"用户表", "表1", User.class);
}