0

我正在使用poi-3.8-20120326.jarExcel 2007,试图在一个列表中收集所有单元格值。

我正在使用公式进行日期增量操作。例如:=(i2+3)对于 k2 单元。

通过我的 java 代码评估这个公式时返回#VALUE!i2是一个日期单元格。)

4

1 回答 1

1

没有来源很难猜出哪里出了问题,但我认为这是你可能会忘记的两件事。

1) 公式评估器

2) 数据格式化程序

看看例子。

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

public class CellReader {

    private Workbook workbook;
    private DataFormatter formatter;
    private FormulaEvaluator evaluator;

    private void openWorkbook(String file) throws FileNotFoundException,
            IOException, InvalidFormatException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);

            workbook = WorkbookFactory.create(fis);
            evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            formatter = new DataFormatter(true);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    private void printXLSX() {
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        int lastRowNum;
        int lastCellNum;
        sheet = workbook.getSheetAt(0);

        lastRowNum = sheet.getLastRowNum();
        for (int j = 0; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            lastCellNum = row.getLastCellNum();
            for (int k = 0; k <= lastCellNum; k++) {
                cell = row.getCell(k);
                if (cell == null) {
                    continue;
                }
                if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) {
                    System.out.println(formatter.formatCellValue(cell));
                } else {
                    System.out.println(formatter.formatCellValue(cell,evaluator));
                }
            }

        }
    }

    public static void main(String[] args) {
        CellReader converter = null;
        try {
            converter = new CellReader();
            converter.openWorkbook("a.xlsx");
            converter.printXLSX();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
于 2012-11-16T12:34:16.723 回答