Java 读取excel文件 行级操作

150 阅读1分钟

当解析的excel文件过大时,可能会造成占用内存过大, 此方法只针对 xlsx格式的excel。

1 工程中引入jar包

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

2 读取方式1

private static void readBigExcel(String filePath) throws FileNotFoundException {
    FileInputStream in = new FileInputStream(filePath);
    StreamingReader reader = StreamingReader.builder()
            .rowCacheSize(100)    // number of rows to keep in memory (defaults to 10)
            .bufferSize(4096)     // buffer size to use when reading InputStream to file (defaults to 1024)
            .sheetIndex(0)        // index of sheet to use (defaults to 0)
            .read(in);            // InputStream or File for XLSX file (required) 
            
    for (Row r : reader) {
        for (Cell c : r) {
            System.out.print(c.getStringCellValue() + "  ");
        }
        System.out.println();
    }
}

3 读取方式2

public static  List<Map<Integer, String>> getStreamWorkbook(String filePath) throws FileNotFoundException {
    FileInputStream in = new FileInputStream(filePath);
    Workbook wk = StreamingReader.builder()
            .rowCacheSize(100)  //缓存到内存中的行数,默认是10
            .bufferSize(4096)   //读取资源时,缓存到内存的字节大小,默认是1024
            .open(in);          //打开资源,可以是InputStream或者是File
            
       Sheet sheet = wk.getSheetAt(0); //取第0张表
       //遍历所有的行
       List<Map<Integer, String>> list = new ArrayList<>();
       for (Row row : sheet) { 
           if (isTitle) { // 跳过第一行标题,需要标题时可以注释掉判断 
               isTitle = false;
               continue; 
           }
           System.out.println("开始遍历第" + row.getRowNum() + "行数据:");
           Map<Integer, String> map = new HashMap<>(); 
           
           //遍历所有的列
          Set<Map.Entry<Integer, Cell>> entries = ((StreamingRow)row).getCellMap().entrySet();           Iterator<Map.Entry<Integer, Cell>> iterator = entries.iterator();
          // 遍历得到键值对,存入新的map中
          while (iterator.hasNext()) { 
              Map.Entry<Integer, Cell> next = iterator.next(); 
              Integer key = next.getKey(); 
              String value = next.getValue().getStringCellValue(); 
              map.put(key, value);
          }
          list.add(map);
      }
       
    return list;
    
    
    
                        好好学习天天向上
                    

原文链接:blog.csdn.net/weixin_3764…