Java中poi读取excel大文件卡死的解决方案

Java中poi读取excel大文件卡死的解决方案

在处理一个10M左右的Excel文件时,意外发现,不管怎么写,当然都是循规蹈矩的写,都会卡死不动,也不抛异常,也不给响应,应该是发生问题了。
经过一系列的搜索,发现了有几种解决方案,其中一种是采用XSSFWorkbook,根据文章描述,XSSFWorkbook是以流的方式进行的处理,但是在做测试时,效果并不理想,最终确定可用的方案如下:

引入monitorjbl/xlsx-streamer依赖

<dependency>
    <groupId>com.monitorjbl</groupId>
    <artifactId>xlsx-streamer</artifactId>
    <version>1.2.0</version>
</dependency>

处理文件

//path为文件路径     获取文件
InputStream stream = new FileInputStream(new File(path));
// 将输入流转换为工作簿对象
Workbook workbook = StreamingReader.builder()
        .rowCacheSize(100)//读取到内存中的行数,默认10
        .bufferSize(4096)//读取资源,缓存到内存的字节大小。默认1024
        .open(stream);//打开资源。只能是xlsx文件
//获取第一个sheet
Sheet sheet = workbook.getSheetAt(0);
try {
    //遍历行
    for (Row row : sheet) {
     System.out.println("开始遍历第" + row.getRowNum() + "行数据:");
     //i可代表哪一列
        int i = 0;
        try {
            //遍历列
            for (Cell cell : row) {
                i++;
                //读取第五行第二列单元格数据
                if (row.getRowNum() == 5) {
                    if (i == 2) {
                        System.out.println(cell.getStringCellValue());
                    }
                }
                //根据某一行第二列单元格中值读取本行第四列单元格的值 
                if (i == 2 && cell.getStringCellValue().equals("小计")) {
                   System.out.println(row.getCell(3).getStringCellValue());
                }
            }
        } catch (Exception e) {
            logger.error("excel文件解析失败");
        }
    }
} catch (Exception e) {
    logger.error("excel文件解析失败");
}
//关闭stream
stream.close();

鸣谢:https://blog.csdn.net/weixin_28862967/article/details/114119029

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注