easyExcel导入
- 从easyexcel官网中拷贝过来,使用到的,这是使用监听器的方法。
EasyExcel.read(file.getInputStream(), BaseStoreDataExcelVo.class, new ReadListener<BaseStoreDataExcelVo>() {public static final int BATCH_COUNT = 100;private List<BaseStoreDataExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);@Overridepublic void invoke(BaseStoreDataExcelVo data, AnalysisContext analysisContext) {cachedDataList.add(data);if (cachedDataList.size() >= BATCH_COUNT) {saveData();cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);}}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {saveData();}private void saveData() {saveAndUpdate(cachedDataList, result);}
}).headRowNumber(3).sheet().doRead();
- 其中headRowNumber是指表头为第三行,数据从第四行开始读取
使用easyExcel导出数据
- 封装了一个导出的工具类,也是使用
easyexcel
public static void exportExcel(HttpServletResponse response, List<?> list,String fileName, Class<?> clazz) throws IOException {if (CollectionUtils.isEmpty(list)) {throw new RuntimeException();}if (StringUtils.isEmpty(fileName)) {fileName = new Date().toString();}String sheetName = fileName;try {response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");Map<Integer,Short> colorMap=new HashMap<>();
ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();EasyExcel.write(response.getOutputStream(), clazz).registerWriteHandler(widthStyleStrategy).registerWriteHandler(new XCellStyleUtils(colorMap)).autoCloseStream(Boolean.FALSE).sheet(sheetName).doWrite(list);} catch (Exception e) {}}
@GetMapping("/downloadStoreSelect")@ApiOperation("数据下载")public void downloadStoreSelect(HttpServletResponse response) {Page<BaseStoreData> baseStoreDataPage = storeDataService.selectPage(null);try {EasyExcelUtils.exportExcel(response, changeData(baseStoreDataPage.getRecords()), "库存.xlsx", BaseStoreDataExcelVo.class);} catch (IOException e) {throw new RuntimeException(e);}}
使用easyExcel下载对应前端代码
downloadStoreSelect().then(response => {const url = window.URL.createObjectURL(new Blob([response.data]));const link = document.createElement('a');link.href = url;link.setAttribute('download', 'export.xlsx'); document.body.appendChild(link);link.click();})