【问题标题】:Apache POI SAX Parsing - How to get actual value of the cellApache POI SAX Parsing - 如何获取单元格的实际值
【发布时间】:2016-11-30 10:37:39
【问题描述】:

我需要使用内存有限的 apache poi 解析非常大的 excel 文件。 google了一下,才知道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
    }
}

在上面链接中提供的示例中,方法“单元格”只能访问格式化值,但我需要访问单元格的实际值。

【问题讨论】:

  • 编写您自己的 SAX 处理程序以传入?
  • 你可以在response看到我的完整示例

标签: java excel apache-poi


【解决方案1】:

流接口的当前实现不提供此功能。因此,为了实现这一点,您需要复制底层XSSFSheetXMLHandler 的代码并对其进行调整,以使单元格内容不被格式化。

【讨论】:

  • 非常感谢@centic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
相关资源
最近更新 更多