2016-10-27 55 views
1

我正在閱讀非常大(150Mb)的xlsx文件。我有我自己的XSSFSheetXMLHandler.SheetContentsHandler來提取感興趣的數據。 (它確實快速執行)。但是,對於每個單元覆蓋的方法使用XSSFSheetXMLHandler獲取樣式信息

cell(String cellReference, String formattedValue, XSSFComment comment) 

只給我的單元格引用和值。

如何獲取應用於此單元格的樣式(以及前景填充顏色)? XSSFSheetXMLHandler給了我StylesTable數據 - 所以我知道存在什麼樣式,我沒有的是從每個單元格到StylesTable的任何類型的指針。唯一的解決方案似乎是擴展XSSFSheetXMLHandler,然後開始反向工程SAX解析。

這是唯一的方法嗎?

回答

1

從Apache POI源代碼抓取XSSFSheetXMLHandler的源代碼;這相當簡單。

我發現克隆這個類來做所有我需要的東西比傳遞一個SheetHandler更有意義。在遇到處理大型XLSX文件的內存問題之前,我能夠實現用戶API完成的所有任務(樣式,顏色,邊框,合併單元格等)。

例如,我對startElement下的「c」處理程序進行了輕微更改。我將XSSFCellStyle保存爲類的一個屬性,然後我可以在cellHandler中使用它。

// c => cell 
     else if ("c".equals(localName)) { 
      // Set up defaults. 
      this.nextDataType = xssfDataType.NUMBER; 
      this.formatIndex = -1; 
      this.formatString = null; 
      cellRef = attributes.getValue("r"); 
      String cellType = attributes.getValue("t"); 
      String cellStyleStr = attributes.getValue("s"); 
      if (stylesTable != null) { 
       if (cellStyleStr != null) { 
        int styleIndex = Integer.parseInt(cellStyleStr); 
        this.cellStyle = stylesTable.getStyleAt(styleIndex); 
       } else if (stylesTable.getNumCellStyles() > 0) { 
        this.cellStyle = stylesTable.getStyleAt(0); 
       } 
      } 

並且(例如,在cellHandler)後使用它:

XSSFFont cellFont = cellStyle.getFont(); 
     if(cellFont.getXSSFColor() != null) { 
      // set hex colour in style. drop first 2 hex characters since they represent alpha 
      styles.put(CSS_COLOR, "#"+cellFont.getXSSFColor().getARGBHex().substring(2)); 
     } 

合併單元:

else if ("mergeCell".equals(localName)) { 
      if (attributes.getValue("ref") != null) { 
       CellRangeAddress cra = CellRangeAddress.valueOf(attributes.getValue("ref")); 
       // store merged cell ranges in hashmap?  
      } 
     }