springboot下导入excel

记录一次导入Excel文件操作的代码
只是记录,没有介绍,想仔细了解可以参考给出的推荐文章

推荐文章:
Springboot下导入导出excel

    @GetMapping("/data/importData")
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseEntity<Object> dataImport(MultipartFile file) {
        if (file == null) {
            return ResponseEntity.badRequest().body("上传文件不能为空!");
        }
        try (InputStream fis = file.getInputStream();
             // 使用文件后缀名判断文件类型
             Workbook workbook = ExcelUtils.getWorkbook(fis, file.getOriginalFilename())) {
            List<AuthStore> records = new ArrayList<>();

            // 遍历所有的Sheet(假设是从第一个到第二个sheet,sheet索引从0开始)
            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);

                // 从2开始,因为0是标题行,1是说明行
                for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue; // 如果该行为空,则跳过
                    }
                    AuthStore authStore = new AuthStore();
                    // 企业名称
                    String name = ExcelUtils.replaceNewlines(ExcelUtils.getCellValue(row.getCell(1)));
                    // 如果商户名称为空,则跳过该行
                    if (StrUtil.isBlank(name)) {
                        // 或者 break; 根据需要决定是否跳过整个sheet
                        continue;
                    }
                    authStore.setName(name);
                    authStore.setBusinessScope("1");
                    authStore.setContactName(ExcelUtils.getFirstLine(ExcelUtils.getCellValue(row.getCell(4))));
                    authStore.setPhone(ExcelUtils.getFirstLine(ExcelUtils.getCellValue(row.getCell(5))));
                    // 处理手机号码格式检查
                    String phone = authStore.getPhone();
                    if (StrUtil.isBlank(phone) || phone.contains("-")) {
                        // 如果手机为空或者包含 "-",使用拼音首字母作为登录名
                        String loginName = PinyinUtils.getPinyinInitials(authStore.getName());
                        loginName = loginName.toLowerCase();
                        // 可以将拼音首字母作为手机号(登录名)
                        authStore.setPhone(loginName);
                    }
                    authStore.setAuthStatus("1");
                    authStore.setAuthById("1");
                    authStore.setType("1"); //线下
                    // 定义日期格式
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
                    Date specificDate = dateFormat.parse("2024.12.14");
                    authStore.setCreateTime(specificDate);
                    // 处理授权开始日期
                    String dateString = ExcelUtils.getFirstLine(ExcelUtils.getCellValue(row.getCell(6)));
                    Date authBeginDate = dateFormat.parse(dateString);
                    authStore.setAuthBeginDate(authBeginDate);
                    // 处理授权结束日期(暂全设置两年后)
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(authBeginDate);
                    // 增加两年
                    calendar.add(Calendar.YEAR, 2);
                    // 获取两年后的日期
                    Date futureDate = calendar.getTime();
                    authStore.setAuthEndDate(futureDate);
                    authStore.setCertCode(TsdmpConstant.DEFAULT_CERT_NUMBER);

                    // 单独处理线上的门店,从第326行开始处理
                    if (i >= 325) {
                        authStore.setContactAddressDetail(ExcelUtils.replaceNewlines(ExcelUtils.getCellValue(row.getCell(2))));
                        // 设置企业介绍
                        authStore.setCompProfile(ExcelUtils.replaceNewlines(ExcelUtils.getCellValue(row.getCell(3))));
                        // 设置线上类型
                        authStore.setType("2"); //线上
                    }else {
                        authStore.setContactAddressDetail(ExcelUtils.replaceNewlines(ExcelUtils.getCellValue(row.getCell(3))));
                    }
                    // 添加到记录列表
                    records.add(authStore);

                }
            }

            // 查询旧的授权门店列表数据
            List<AuthStore> oldRecords = authStoreService.list();

            // 处理当前新的授权门店列表数据,和之前旧的授权门店列表数据,进行比对,新的list拆分成两个,一个是完全不包含旧的list相同数据,一个是与旧的相同的数据
            List<AuthStore> sameList = new ArrayList<>();
            List<AuthStore> differentList = new ArrayList<>(records); // Copy newList to start with

            Iterator<AuthStore> iterator = differentList.iterator();
            while (iterator.hasNext()) {
                AuthStore newData = iterator.next();
                for (AuthStore oldData : oldRecords) {
                    if (newData.getName().equals(oldData.getName())) {
                        newData.setId(oldData.getId());
                        newData.setPhone(oldData.getPhone());
                        newData.setLatitude(oldData.getLatitude());
                        newData.setLongitude(oldData.getLongitude());
                        sameList.add(newData);
                        iterator.remove(); // Remove from differentList
                        break;
                    }
                }
            }

//            //与原先不同的
//            List<AuthStore> difList = new ArrayList<>(oldRecords);
//            Iterator<AuthStore> iterator1 = difList.iterator();
//            while (iterator1.hasNext()) {
//                AuthStore newData = iterator1.next();
//                for (AuthStore oldData : sameList) {
//                    if (newData.getName().equals(oldData.getName())) {
//                        iterator1.remove(); // Remove from differentList
//                        break;
//                    }
//                }
//            }
//            log.info("重合的与原来不同记录数:{}", difList.size());

            log.info("相同记录数:{}", sameList.size());
            log.info("不同记录数:{}", differentList.size());

            // 批量更新数据
            //authStoreService.updateBatchById(sameList);

            // 保存或更新批量记录
            boolean status = authStoreService.saveOrUpdateBatch(differentList);



            log.info("总记录数:{}", records.size());
            return ResponseEntity.ok(differentList);
        } catch (Exception e) {
            log.error("异常:", e);
        }
        // 立即响应前端
        return ResponseEntity.ok("数据同步已开始,请稍后查看日志以获取同步结果");
    }

Excel表导入的工具类

/**
 * excel表导入工具类
 *
 * @author CACSIOT
 */
public class ExcelUtils {

    /**
     * 根据文件后缀名获取对应的 Workbook
     */
    public static Workbook getWorkbook(FileInputStream fis, String excelFilePath) throws IOException {
        if (excelFilePath.endsWith("xlsx")) {
            return new XSSFWorkbook(fis);
        } else if (excelFilePath.endsWith("xls")) {
            return new HSSFWorkbook(fis);
        } else {
            throw new IllegalArgumentException("文件格式不支持: " + excelFilePath);
        }
    }

    /**
     * 根据文件后缀名获取对应的 Workbook
     */
    public static Workbook getWorkbook(InputStream inputStream, String excelFilePath) throws IOException {
        // 处理 .xlsx 文件
        if (excelFilePath.endsWith("xlsx")) {
            return new XSSFWorkbook(inputStream);
        } else if (excelFilePath.endsWith("xls")) {
            // 处理 .xls 文件
            return new HSSFWorkbook(inputStream);
        } else {
            throw new IllegalArgumentException("文件格式不支持: " + excelFilePath);
        }
    }

    /**
     * 用 WorkbookFactory 来自动识别文件类型
     */
    public static Workbook getWorkbook(InputStream inputStream) throws IOException {
        try {
            // 使用 WorkbookFactory 来自动识别文件类型
            return WorkbookFactory.create(inputStream);
        } catch (InvalidFormatException e) {
            throw new IllegalArgumentException("无法识别文件格式", e);
        }
    }

    /**
     * 从 Excel 单元格中获取值
     */
    public static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                // 处理数字时,判断是否为整数
                if (DateUtil.isCellDateFormatted(cell)) {
                    // 处理日期格式
                    return cell.getDateCellValue().toString();
                } else {
                    // 处理联系电话等数值型数据
                    return BigDecimal.valueOf(cell.getNumericCellValue()).toPlainString();
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                // 如果单元格是公式,取计算后的值
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    /**
     * 处理行列的方法
     */
    public static String getCellValueMethod(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((int) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    /**
     * 替换单元格内容中的换行符为指定分隔符
     */
    public static String replaceNewlines(String cellValue) {
        if (cellValue != null) {
            // 将换行符替换为反斜杠
            return cellValue.replace("\n", "/");
        }
        return cellValue;
    }

    /**
     * 获取单元格内容的第一行(按换行符分割)
     */
    public static String getFirstLine(String cellValue) {
        if (cellValue != null) {
            // 按换行符分割,并返回第一个部分
            String[] lines = cellValue.split("\n");
            return lines[0]; // 返回第一行
        }
        return cellValue; // 如果为空,直接返回原值
    }

    /**
     * 获取单元格的值,处理公式
     *
     * @param cell             单元格
     * @param formulaEvaluator 公式评估器
     * @return 单元格的值
     */
    public static String getCellValue(Cell cell, FormulaEvaluator formulaEvaluator) {
        if (cell == null) {
            return null;
        }
        // 获取单元格的实际值,评估公式
        switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
            case NUMERIC:
                // 如果是数字类型,可能是日期或普通数字
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 处理浮动数字类型
                    double numericValue = cell.getNumericCellValue();
                    // 如果是整数(如589.0),可以返回整数部分
                    if (numericValue == (int) numericValue) {
                        return String.valueOf((int) numericValue);
                    } else {
                        return String.valueOf(numericValue); // 保持浮动类型
                    }
                }
            case STRING:
                return cell.getStringCellValue();
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                // 公式单元格的结果
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
                    case NUMERIC:
                        return String.valueOf(cell.getNumericCellValue());
                    case STRING:
                        return cell.getStringCellValue();
                    default:
                        return "";
                }
            case BLANK:
                return "";
            default:
                return "";
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值