采用常规的导入方法会导致内存异常,这里使用
monitorjbl开源jar包来处理
引入maven包
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.0.0</version> </dependency> <!-- 读取大量excel数据时使用 --> <dependency> <groupId>com.monitorjbl</groupId> <artifactId>xlsx-streamer</artifactId> <version>2.1.0</version> </dependency>
1、读取文件 List<List<Object>> returnList = new ArrayList<>(); InputStream is = null; try { is = file.getInputStream(); Workbook wk= StreamingReader.builder() .rowCacheSize(100) //缓存到内存中的行数,默认是10 .bufferSize(4096) //读取资源时,缓存到内存的字节大小,默认是1024 .open(is); //获取第一个表单sheet Sheet sheet = wk.getSheetAt(0);
2、循环所有行
for (Row row :sheet) { i++; if (i < 4){ continue; } if (row != null) { //获取这一行的第一列 int firstcell = row.getFirstCellNum(); //获取这一行的最后一列 int lastcell = column; //创建一个集合,用处将每一行的每一列数据都存入集合中 List<Object> list = new ArrayList<>(); for (int j = firstcell; j < lastcell; j++) { //获取第j列 Cell cell = row.getCell(j); if (cell != null) { Object o = cell.getStringCellValue(); list.add(o); } else { list.add(null); } } returnList.add(list); } }