• 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>
    
    • 1
    • 2
    • 3
    • 4
    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} `)
            }
          }
        },
    }	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
     return csBalanceAgentService.importExcelData(file);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    @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("导入成功");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    以下代码可以替换上面的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("导入成功");
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    // 辅助方法,获取单元格的值,包括公式结果处理
    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。
    // 获取单元格类型,根据不同的类型进行相应的处理。
    // 当单元格类型为公式时,需要使用公式求值器来获取计算结果。
    // 接下来根据计算结果的类型,返回相应的值。
    // 若为数值类型,则返回数值的字符串表示。
    // 若为字符串类型,则直接返回字符串值。
    // 若为布尔类型,则返回布尔值的字符串表示。
    // 若为错误类型,则根据错误值获取对应的错误字符串
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    这段代码用于从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单元格的值,并根据需要进行解析和转换。此方法可能需要根据您的具体需求进行修改。另外,错误处理部分只是简单的打印了异常堆栈信息,您可以根据实际情况进行适当修改。

  • 相关阅读:
    Linux系统运行时参数命令
    详解 C++ 实现K-means算法
    毕设选题推荐基于python的django框架医院预约挂号系统
    Codeforces Round #836 (Div. 2)
    GD32搭建Keil MDK开发环境
    R数据分析:扫盲贴,什么是多重插补
    微处理器性能简介(8086)
    【C++】智能指针【内存泄漏|智能指针原理及使用|RAII】
    排列组合总结
    js--滚轮事件
  • 原文地址:https://blog.csdn.net/PIKapikaaaa/article/details/134017061