我正在使用poi-3.8-20120326.jar
和Excel 2007,尝试在一个列表中收集所有单元格值。
我正在使用公式进行日期增量操作。例如:=(i2+3)
表示k2单元格。
通过我的java代码评估此公式时,返回#VALUE!
(i2
是一个日期单元格。)
答案 0 :(得分:1)
没有消息来源,很难猜出什么是错的,但我认为这是你可能忘记的两件事。
1)FormulaEvaluator
2)DataFormatter
看看例子。
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();
}
}
}