EasyPOI批量导入

目录

1.首先引入依赖

2.定义导出数据基本对象

3.导入Excel中数据

4.然后就得到了导入的对象集合,再进行具体的业务处理


1.首先引入依赖

 <!--引入easypoi依赖-->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.1.0</version>
</dependency>

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.1.0</version>
</dependency>

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.1.0</version>
</dependency>

2.定义导出数据基本对象

注意: 这里的实体类需要进行序列化

如果是多个sheef,分别创建每个sheef对应的实体并序列化。

实体上添加@ExcelTarget()注解,字段上添加 @Excel()注解。

另外再添加一个errorMsg用于导出时生成错误信息的列,后期进行判断的时候,也是把错误信息放在该字段中

@Data
@ExcelTarget("QuestionBankImport")
public class QuestionBankImport implements Serializable {
    @Excel(name = "分类")
    private String classification;

    @Excel(name = "类型")
    private String questionTypes;

    @Excel(name = "错误信息")
    private String errorMsg;
}

3.导入Excel中数据

导入第一个sheef

//导入参数
ImportParams params = new ImportParams();
params.setTitleRows(1);//标题列占几行
params.setHeadRows(1);//header列占几行
params.setStartSheetIndex(0);
ZipSecureFile.setMinInflateRatio(-1.0d);

//获取导入数据
List<QuestionBankImport> qbiList = new ArrayList<>();
try {         
     qbiList = ExcelImportUtil.importExcel(new FileInputStream(filePath), QuestionBankImport.class, params);
} catch (Exception e) {
      log.info(e.getMessage());
}

导入第二个sheef

//导入
ImportParams param = new ImportParams();
param.setTitleRows(0);//标题列占几行
param.setHeadRows(1);//header列占几行

param.setStartSheetIndex(1);//读取第二个sheet
List<OutletsPostImport> opiList = null;
try {
    opiList = ExcelImportUtil.importExcel(new FileInputStream(filePath), OutletsPostImport.class, param);
} catch (Exception e) {
    log.info(e.getMessage());
}

导入第三个sheef

//导入
ImportParams param = new ImportParams();
param.setTitleRows(0);//标题列占几行
param.setHeadRows(1);//header列占几行

param.setStartSheetIndex(2);//读取第三 个sheet
List<OutletsInvestmentImport> oiList = null;
try {
     oiList = ExcelImportUtil.importExcel(new FileInputStream(filePath), OutletsInvestmentImport.class, param);
} catch (Exception e) {
    log.info(e.getMessage());
}

如果有错误就生成错误文件

File file = FileUtil.touch(tempFilePath);

//导出单个sheet
//ExportParams exportParams = new ExportParams();
//Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null,"XX网点"),OutletsPostImport.class, errListPost);

//导出多个sheet
// 创建参数对象(用来设定excel得sheet得内容等信息)
ExportParams outletsBasicExportParams = new ExportParams();
// 设置sheet得名称
outletsBasicExportParams.setSheetName("AAA网点");
//.xslx格式 默认为.xls格式
outletsBasicExportParams.setType(ExcelType.XSSF);
// 创建sheet1使用得map
Map<String, Object> basicExportMap = new HashMap<>();
// title的参数为ExportParams类型,目前仅仅在ExportParams中设置了sheetName
basicExportMap.put("title", outletsBasicExportParams);
// 模版导出对应得实体类型
basicExportMap.put("entity", OutletsBasicImport.class);
// sheet中要填充得数据
basicExportMap.put("data", errList);

ExportParams outletsPostExportParams = new ExportParams();
//.xslx格式 默认为.xls格式
outletsPostExportParams.setType(ExcelType.XSSF);
outletsPostExportParams.setSheetName("BBB网点");
// 创建sheet2使用得map
Map<String, Object> postExportMap = new HashMap<>();
postExportMap.put("title", outletsPostExportParams);
postExportMap.put("entity", OutletsPostImport.class);
postExportMap.put("data", errListPost);


ExportParams outletsInvestmentExportParams = new ExportParams();
//.xslx格式 默认为.xls格式
outletsInvestmentExportParams.setType(ExcelType.XSSF);
outletsInvestmentExportParams.setSheetName("CCC网点");
// 创建sheet2使用得map
Map<String, Object> investmentExportMap = new HashMap<>();
investmentExportMap.put("title", outletsInvestmentExportParams);
investmentExportMap.put("entity", OutletsInvestmentImport.class);
investmentExportMap.put("data", errListInvestment);

// 将sheet1、sheet2、sheet3使用得map进行包装
List<Map<String, Object>> sheetsList = new ArrayList<>();
sheetsList.add(basicExportMap);
sheetsList.add(postExportMap);
sheetsList.add(investmentExportMap);
// 执行方法 导出.xlsx格式
Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.XSSF);

FileOutputStream outputStream = null;
try {
    outputStream = new FileOutputStream(tempFilePath);
} catch (FileNotFoundException e) {
    log.info(e.getMessage());
}
try {
    workbook.write(outputStream);
    outputStream.close();
    workbook.close();
} catch (IOException e) {
    log.info(e.getMessage());
}

realPath = fileBasePath + ResourceUtil.createFileName("xlsx");
//将文件上传到sftp
Sftp sftp = SftpUtil.getSftp();
SftpUtil.upload(sftp, cp2.getAstr(), realPath);
SftpUtil.close(sftp);

4.然后就得到了导入的对象集合,再进行具体的业务处理

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用 Easypoi 实现批量导入 Excel 数据并返回校验失败的数据,并将其写入 Excel 文件,可以按照以下步骤进行操作: 1. 定义一个 Excel 实体类,用于存储导入的 Excel 数据,同时添加校验注解,如下所示: ```java public class UserExcelEntity implements Serializable { @Excel(name = "姓名", orderNum = "0") @NotBlank(message = "姓名不能为空") private String name; @Excel(name = "年龄", orderNum = "1") @Range(min = 1, max = 200, message = "年龄范围必须在1-200之间") private Integer age; // ... 其他属性和校验注解 } ``` 2. 定义一个导入工具类,使用 Easypoi 实现批量导入 Excel 数据,并返回校验失败的数据,如下所示: ```java public class ExcelImportUtil { public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz, List<String> errorMsg) throws Exception { List<T> successList = new ArrayList<>(); List<T> errorList = new ArrayList<>(); ImportParams params = new ImportParams(); params.setTitleRows(1); params.setHeadRows(1); ExcelImportResult<T> result = ExcelImportUtil.importExcelMore(file.getInputStream(), clazz, params); List<T> list = result.getList(); for (T obj : list) { Set<ConstraintViolation<T>> validateSet = Validation.buildDefaultValidatorFactory().getValidator().validate(obj); if (validateSet.isEmpty()) { successList.add(obj); } else { errorMsg.add(buildErrorMsg(validateSet)); errorList.add(obj); } } if (!errorList.isEmpty()) { String fileName = "error_" + System.currentTimeMillis() + ".xlsx"; String filePath = "D:/excel/" + fileName; ExportParams exportParams = new ExportParams(); Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, errorList); FileOutputStream fos = new FileOutputStream(filePath); workbook.write(fos); fos.close(); } return successList; } private static <T> String buildErrorMsg(Set<ConstraintViolation<T>> validateSet) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<T> validate : validateSet) { sb.append(validate.getPropertyPath().toString()).append(":").append(validate.getMessage()).append(";"); } return sb.toString(); } } ``` 3. 在Controller中调用导入工具类,将校验失败的数据写入 Excel 文件,并返回校验成功的数据,如下所示: ```java @PostMapping("/import") public Result importExcel(@RequestParam("file") MultipartFile file) throws Exception { List<String> errorMsg = new ArrayList<>(); List<UserExcelEntity> list = ExcelImportUtil.importExcel(file, UserExcelEntity.class, errorMsg); if (!errorMsg.isEmpty()) { return Result.error("部分数据导入失败,请下载错误文件查看详情!"); } // 保存校验成功的数据 userService.saveBatch(list); return Result.success("数据导入成功!"); } ``` 其中,将校验失败的数据写入 Excel 文件的代码如下: ```java if (!errorList.isEmpty()) { String fileName = "error_" + System.currentTimeMillis() + ".xlsx"; String filePath = "D:/excel/" + fileName; ExportParams exportParams = new ExportParams(); Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, errorList); FileOutputStream fos = new FileOutputStream(filePath); workbook.write(fos); fos.close(); } ``` 这里使用了 Easypoi 的 `ExcelExportUtil.exportExcel()` 方法,将校验失败的数据导出为 Excel 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值