Spring Boot 导出EXCEL模板以及导入EXCEL数据(阿里Easy Excel实战)
-
导入pom依赖
-
编写导出模板
@ApiOperation("导出xxx模板") @GetMapping("/downTemplates") public void download(HttpServletResponse response) throws FileNotFoundException, IOException { response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); File temFile=new File("src/main/resources/templates/xxx导入模版.xlsx"); String fileName = URLEncoder.encode("xxx导入模版", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8' '" + fileName +".xlsx"); FileCopyUtils.copy(new FileInputStream(temFile), response.getOutputStream()); response.getOutputStream().close(); }
-
导入数据处理
-
编写监听器
@Component public class xxxListener extends AnalysisEventListener<Entity> { private static final Logger LOGGER = LoggerFactory.getLogger(xxxListener.class); //读取数据初始化值 private static final int BATCH_COUNT = 50; List<Entity> list = new ArrayList<Entity>(); @Resource private xxxxService xxxxService; public xxxxListener() { xxxxService=new xxxxServiceImpl(); } public xxxxListener(xxxxService xxxxService) { this.xxxxService=xxxxService; } @Override public void invoke(xxxx data, AnalysisContext analysisContext) { list.add(data); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { saveData(); // 存储完成清理 list list.clear(); } } /** * 所有excel表中数据解析完成了 都会来调用这个 * 解释为什么要保存数据? *初始化读取数量为50,表中信息已经加载完毕,,假设excel表中最后只剩下30行遗留数据,所以为了防止存在遗留数据 尽量判断下集合是否为空,不为空在进行存储(这是我的逻辑需要判断,如果不需要也可进行不判断) * @param analysisContext */ @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { if(list.size()==0){ return; } saveData(); LOGGER.info("所有数据解析完成!"); } private void saveData() { //代码实现类层保存数据 xxxxService.saveBatch(list); LOGGER.info("存储数据库成功!"); }
-
编写数据转换器
public class XXXConverter implements Converter<Integer> { //在java中保护单位是用数字来标识的所以是int @Override public Class supportJavaTypeKey() { return Integer.class; } // 在excel中是string @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } //将excel的数据类型转为java数据类型 @Override public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { String stringValue = cellData.getStringValue(); if (stringValue == null) { throw new RuntimeException("数据为空"); } if ("(自己的数据)".equals(stringValue)) { return 1; } return 0; } //将java的数据类型转为excel数据类型 @Override public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { return new WriteCellData<>(); } }
-