EasyPoi导入

EasyPoi导入

<a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
          @change="handleImportExcel">
  <a-button type="primary" icon="import">导入数据</a-button>
</a-upload>
data() {
    return {
      url: {
        importExcelUrl: 'cs/csBalanceAgent/importExcel'
      }
    }
  },
methods: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    /* 导入 */
    handleImportExcel(info) {
      console.log('info-----------------', info)
      this.loading = true
      if (info.file.status !== 'uploading') {
        console.log('file==================', info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.loading = false
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                  <span>{msg}</span><br />
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          // this.loadData()
          this.$refs.tablePage.refreshTable()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.loading = false
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉,登录已过期,请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
}	
/**
 * 通过excel导入数据
 *
 * @return
 */
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
 return csBalanceAgentService.importExcelData(file);
}
@Override
public Result<?> importExcelData(MultipartFile file) {
    List<CsBalanceAgent> list = null;

    ImportParams importParams = new ImportParams();
    importParams.setTitleRows(1);
    importParams.setHeadRows(2);

    try {
        list = ExcelImportUtil.importExcel(file.getInputStream(), CsBalanceAgent.class, importParams);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (list == null) {
        return Result.error("没有有效的数据,导入数据失败");
    }

    this.saveBatch(list);
    return Result.OK("导入成功");
}

以下代码可以替换上面的importExcelData方法

@Override
public Result<?> importExcelData(MultipartFile file) {
    List<CsCustomNeed> list = null;
    
    // 设置Excel导入参数
    ImportParams importParams = new ImportParams();
    importParams.setTitleRows(1); // 标题行数,即Excel中的第一行是标题行
    importParams.setHeadRows(2); // 表头行数,即Excel中的第二行是表头行
    
    try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
        Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

        list = new ArrayList<>(); // 创建一个空的列表来存储解析后的数据
        int rowCount = sheet.getLastRowNum(); // 获取行数,excel中的行数从0开始
        for (int rowIndex = importParams.getHeadRows(); rowIndex <= rowCount; rowIndex++) {
            Row row = sheet.getRow(rowIndex); // 获取当前行
            
            if (row != null) {
                CsCustomNeed obj = new CsCustomNeed(); // 创建CsCustomNeed对象
                
                // 设置对象属性值,根据实际需求进行修改
                obj.setConsignee(getCellValue(row.getCell(0))); // 设置第一列的值
                obj.setProductPackage(getCellValue(row.getCell(1))); // 设置第二列的值
                obj.setNeedNum(getCellValue(row.getCell(2))); // 设置第三列的值
                obj.setQualityRequire(getCellValue(row.getCell(3))); // 设置第四列的值
                obj.setFormula(getCellValue(row.getCell(4))); // 设置第五列的值
                obj.setPackageRequire(getCellValue(row.getCell(5))); // 设置第六列的值
                obj.setDeliveryTime(getCellValue(row.getCell(6))); // 设置第七列的值
                obj.setRemark(getCellValue(row.getCell(7))); // 设置第八列的值
                
                list.add(obj); // 将当前行的对象添加到列表中
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    if (list == null || list.isEmpty()) {
        return Result.error("没有有效的数据,导入数据失败");
    }
    
    this.saveBatch(list); // 批量保存数据
    return Result.OK("导入成功");
}

// 辅助方法,获取单元格的值,包括公式结果处理
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}

    // 获取单元格类型
    CellType cellType = cell.getCellType();
    if (cellType == CellType.FORMULA) {
        // 如果单元格类型为公式,需要通过公式求值器获取计算结果
        FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
        CellValue cellValue = evaluator.evaluate(cell);
        cellType = cellValue.getCellType();
        
        // 根据单元格类型返回相应的值
        if (cellType == CellType.NUMERIC) {
            return String.valueOf(cellValue.getNumberValue());
        } else if (cellType == CellType.STRING) {
            return cellValue.getStringValue();
        } else if (cellType == CellType.BOOLEAN) {
            return String.valueOf(cellValue.getBooleanValue());
        } else if (cellType == CellType.ERROR) {
            return ErrorEval.getText(cellValue.getErrorValue());
        } else {
            return null;
        }
    } else if (cellType == CellType.NUMERIC) {
        return String.valueOf(cell.getNumericCellValue());
    } else if (cellType == CellType.STRING) {
        return cell.getStringCellValue();
    } else if (cellType == CellType.BOOLEAN) {
        return String.valueOf(cell.getBooleanCellValue());
    } else {
        return null;
    }
}

/**
 * 详细解释getCellValue()方法的功能。
 * 
 * @param cell 单元格对象
 * @return 单元格的值
 */
// 解释开始
// 此方法用于获取单元格的值,包括公式结果的处理。
// 首先判断单元格是否为空,如果为空则返回null。
// 获取单元格类型,根据不同的类型进行相应的处理。
// 当单元格类型为公式时,需要使用公式求值器来获取计算结果。
// 接下来根据计算结果的类型,返回相应的值。
// 若为数值类型,则返回数值的字符串表示。
// 若为字符串类型,则直接返回字符串值。
// 若为布尔类型,则返回布尔值的字符串表示。
// 若为错误类型,则根据错误值获取对应的错误字符串

这段代码用于从Excel文件中导入数据,并将数据保存到数据库中。以下是对代码的详细解释:

  1. 首先,设置了Excel导入的参数,如标题行数和表头行数。
  2. 使用WorkbookFactory.create(file.getInputStream())方法打开Excel文件,并创建一个Workbook对象。
  3. 获取第一个工作表(Sheet)。
  4. 创建一个空的列表来存储解析后的数据。
  5. 获取工作表的行数,并遍历每一行。
  6. 获取当前行(Row)对象。
  7. 对于不为空的行,创建一个CsCustomNeed对象。
  8. 设置CsCustomNeed对象的属性值,根据Excel中的列顺序来设置对应的属性值。
  9. 将CsCustomNeed对象添加到列表中。
  10. 如果列表为空,则返回导入失败的结果。
  11. 调用saveBatch(list)方法,使用批量操作将数据保存到数据库中。
  12. 返回导入成功的结果。

请注意,代码中的getCellValue()方法用于获取Excel单元格的值,并根据需要进行解析和转换。此方法可能需要根据您的具体需求进行修改。另外,错误处理部分只是简单的打印了异常堆栈信息,您可以根据实际情况进行适当修改。

### 关于 EasyPoi 导入功能的使用教程 #### 易用性与配置简介 EasyPoi 是一款用于简化 Java 应用程序中 Excel 文件操作的强大工具库,支持快速实现文件读写等功能。对于 Spring Boot 项目而言,集成 EasyPoi 可以极大提高开发效率并减少重复劳动。 #### Maven依赖引入 为了能够在项目里使用 EasyPoi 进行 Excel 处理,在 `pom.xml` 中添加如下依赖[^1]: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>${latest.version}</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>${latest.version}</version> </dependency> ``` #### 创建实体类 定义好要映射到表格列的据模型非常重要。下面是一个简单的例子展示了如何创建一个包含基本验证逻辑的实体类: ```java @Data public class UserImportDTO implements IExcelDataModel { @Excel(name="用户名", orderNum = "0") private String username; @Excel(name="密码", type=2, isExport=false) private String password; } ``` 注意这里的字段标注了 `@Excel` 注解用来指定对应表头名称以及其它属性设置;同时还可以加入 Hibernate Validator 提供的各种约束条件来增强输入合法性检查能力[^3]。 #### 编写控制器方法处理上传请求 编写相应的 Controller 来接收前端传来的文件流,并调用服务层完成实际业务逻辑: ```java @PostMapping("/importUser") @ResponseBody public AjaxResult importUser(@RequestParam MultipartFile file){ try{ List<UserImportDTO> list = ExcelImportUtil.importExcel(file.getInputStream(), UserImportDTO.class); // 对list做进一步加工... return AjaxResult.success(); }catch(Exception e){ log.error(e.getMessage()); return AjaxResult.error("导入失败!"); } } ``` 上述代码片段演示了一个典型的 RESTful API 接口设计模式,它负责解析客户端提交过来的 .xlsx/.xls 类型文档并将其中的内容转换成内存里的对象列表形式以便后续操作. 针对 Collection 内部元素无法有效触发校验器的问题,则建议先通过自定义的方式获取全部记录后再统一执行二次审核流程确保据质量[^2].
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮卡丘不断更

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值