java大批量导入excel,多线程加分片处理的dome

 废话不多说,直接贴demo

public void importExcel(File file, int batchSize, int threadCount) throws Exception {
    // 创建 Excel 读取器
    ExcelReader reader = new ExcelReaderBuilder(new FileInputStream(file), null, new ImportDataListener())
            .headRowNumber(1)
            .build();

    // 获取表格中总行数
    ReadSheet sheet = reader.excelExecutor().sheet(0);
    Long totalRows = sheet.getHeadRowNumber() + sheet.getTotalRowNumber() - 1;

    // 计算分片大小和分片数量
    int shardSize = batchSize * threadCount;
    int shardNum = (int) Math.ceil(totalRows * 1.0 / shardSize);

    // 创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);

    // 使用 CountDownLatch 控制主线程的等待
    CountDownLatch countDownLatch = new CountDownLatch(shardNum);

    try {
        // 分片读取并处理 Excel 数据
        for (int i = 0; i < shardNum; i++) {
            // 计算当前分片的起始位置和结束位置
            int startIndex = i * shardSize;
            int endIndex = Math.min(startIndex + shardSize, totalRows.intValue());

            // 提交任务到线程池中处理
            executorService.submit(() -> {
                try {
                    List<List<String>> data = reader.read(sheet, ReadRowHolder.class,
                            new ReadRowHolder(startIndex, endIndex)).getData();
                    // 处理数据,具体处理逻辑可根据自己的业务需求进行编写

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        // 主线程等待所有任务完成
        countDownLatch.await();
    } finally {
        // 关闭线程池和 Excel 读取器
        executorService.shutdown();
        reader.close();
    }
}

/**
 * 用于 Excel 数据读取时分片读取数据
 */
private static class ReadRowHolder implements RowMapper<List<String>> {

    private int startIndex;
    private int endIndex;

    public ReadRowHolder(int startIndex, int endIndex) {
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    @Override
    public List<String> mapRow(Row row) {
        int rowNum = row.getRowNum() + 1;
        if (rowNum < startIndex || rowNum > endIndex) {
            return null; // 非当前分片数据行,忽略
        }
        List<String> rowData = new ArrayList<>();
        int colNum = row.getLastCellNum(); // 获取当前行最后一个单元格的列号
        for (int i = 0; i < colNum; i++) {
            Cell cell = row.getCell(i);
            String cellValue = cell == null ? null : cell.getStringCellValue();
            rowData.add(cellValue);
        }
        return rowData; // 返回读取到的数据
    }
}

/**
 * 用于 Excel 数据读取时处理每一行数据
 */
private static class ImportDataListener extends AnalysisEventListener<List<String>> {

    @Override
    public void invoke(List<String> rowData, AnalysisContext context) {
        // 处理数据,具体处理逻辑可根据自己的业务需求进行编写
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 数据读取完成后的操作,如释放资源等
    }
}

importExcel 方法接收一个 Excel 文件对象、批大小 batchSize 和线程数 threadCount 作为参数。首先,使用 ExcelReader 对象读取 Excel 文件,并计算出总行数和分片大小和数量;然后,创建一个固定数量的线程池,使用 CountDownLatch 控制主线程等待所有任务完成;最后,循环迭代分片区间,将分片任务提交到线程池中处理。在每个任务中,使用 ReadRowHolder 对象实现分片读取 Excel 数据,并使用 ImportDataListener 处理每一行数据。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java 中解析 Excel 数据可以使用 Apache POI 库。下面是一个简单的示例代码,演示如何在多线程环境中解析 Excel 数据: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExcelParser { public static void main(String[] args) { String filePath = "path/to/your/excel/file.xlsx"; int numThreads = 4; // 设置线程数 ExecutorService executor = Executors.newFixedThreadPool(numThreads); try (Workbook workbook = new XSSFWorkbook(new FileInputStream(filePath))) { Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 int numRows = sheet.getPhysicalNumberOfRows(); for (int i = 0; i < numRows; i++) { Row row = sheet.getRow(i); if (row != null) { // 在这里处理每一行的数据,可以将解析的任务提交给线程池 executor.submit(() -> processRow(row)); } } } catch (Exception e) { e.printStackTrace(); } finally { executor.shutdown(); } } private static void processRow(Row row) { int numCells = row.getPhysicalNumberOfCells(); for (int i = 0; i < numCells; i++) { Cell cell = row.getCell(i); if (cell != null) { // 在这里处理每个单元格的数据 String cellValue = cell.toString(); System.out.println("Cell Value: " + cellValue); } } } } ``` 请替换 `filePath` 变量为你的 Excel 文件的路径,并根据需要调整线程数。在 `processRow` 方法中,你可以根据实际需求处理每个单元格的数据。这个示例中使用了 `System.out.println` 打印单元格的值,你可以根据自己的需求进行处理
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

随风奔跑的十八岁

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

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

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

打赏作者

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

抵扣说明:

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

余额充值