解决java中poi读取excel大文件内存溢出的问题

引入依赖

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

解决方案

//path为文件路径     获取文件
        InputStream stream = new FileInputStream(new File(path));
        // 将输入流转换为工作簿对象
        Workbook wb = StreamingReader.builder()
                .rowCacheSize(100)//读取到内存中的行数,默认10
                .bufferSize(4096)//读取资源,缓存到内存的字节大小。默认1024
                .open(stream);//打开资源。只能是xlsx文件
        //获取第一个sheet
        Sheet rows = wb.getSheetAt(0);
        try {
        	//遍历行
            for (Row row : rows) {
           	 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();
经验分享 程序员 微信小程序 职场和发展