2016-11-30 60 views
1

私は非常に大きなExcelファイルを制限メモリ付きのapache poiを使って解析する必要がありました。グーグルでは、poiが大量のメモリを消費することなく、大きなファイルを効果的にパーサーするためにSAXパーサーを提供することを知りました。上記リンクに設けられた例でApache POI SAX解析 - セルの実際の値を取得する方法

Apache POI SAX Parser example

private class SheetToCSV implements SheetContentsHandler { 
    private boolean firstCellOfRow = false; 
    private int currentRow = -1; 
    private int currentCol = -1; 

    private void outputMissingRows(int number) { 
     for (int i=0; i<number; i++) { 
      for (int j=0; j<minColumns; j++) { 
       output.append(','); 
      } 
      output.append('\n'); 
     } 
    } 

    @Override 
    public void startRow(int rowNum) { 
     // If there were gaps, output the missing rows 
     outputMissingRows(rowNum-currentRow-1); 
     // Prepare for this row 
     firstCellOfRow = true; 
     currentRow = rowNum; 
     currentCol = -1; 
    } 

    @Override 
    public void endRow(int rowNum) { 
     // Ensure the minimum number of columns 
     for (int i=currentCol; i<minColumns; i++) { 
      output.append(','); 
     } 
     output.append('\n'); 
    } 

    @Override 
    public void cell(String cellReference, String formattedValue, 
      XSSFComment comment) { 
     if (firstCellOfRow) { 
      firstCellOfRow = false; 
     } else { 
      output.append(','); 
     } 

     // gracefully handle missing CellRef here in a similar way as XSSFCell does 
     if(cellReference == null) { 
      cellReference = new CellAddress(currentRow, currentCol).formatAsString(); 
     } 

     // Did we miss any cells? 
     int thisCol = (new CellReference(cellReference)).getCol(); 
     int missedCols = thisCol - currentCol - 1; 
     for (int i=0; i<missedCols; i++) { 
      output.append(','); 
     } 
     currentCol = thisCol; 

     // Number or string? 
     try { 
      Double.parseDouble(formattedValue); 
      output.append(formattedValue); 
     } catch (NumberFormatException e) { 
      output.append('"'); 
      output.append(formattedValue); 
      output.append('"'); 
     } 
    } 

    @Override 
    public void headerFooter(String text, boolean isHeader, String tagName) { 
     // Skip, no headers or footers in CSV 
    } 
} 

Iは、セルの実際の値にアクセスする必要があるが、メソッド「セル」が唯一の書式の値へのアクセスを有します。

+0

渡すSAXハンドラを作成しますか? – Gagravarr

答えて

2

ストリーミングインターフェイスの現在の実装では、これが提供されていません。したがって、これを実現するには、基底のコードXSSFSheetXMLHandlerをコピーし、セル内容がフォーマットされないように調整する必要があります。

+0

ありがとう@centic – Arul

関連する問題