【发布时间】:2017-07-26 11:31:02
【问题描述】:
所以我的 Java 代码是这样读取 excel 表单元格值的,但我无法将日期的值作为字符串获取,而是自动更正为数字。另请注意,所有这些 excel 值都是通过各自单元格中的公式计算的。缺少什么?
public class DatasheetReader {
public static void main(String args[]) throws Exception {
String path = "D:\\Workspace\\Analytics\\TestDataSheets\\IRPTestData.xlsx";
String sheet = "CompleteSimulationData";
getCellData(path, sheet);
}
public static Object[][] getCellData(String datSheetPath, String sheetName)throws Exception {
FileInputStream fis = new FileInputStream(new java.io.File(datSheetPath));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();
// System.out.println(rowCount);
// System.out.println(columnCount);
Object[][] cellData = new Object[rowCount][columnCount];
Object[][] dataProviderArray = new Object[rowCount - 1][columnCount];
for (int i = 0; i < rowCount; i++) {
System.out.println(" ");
for (int j = 0; j < columnCount; j++) {
// IF - for blanks in excel
if (i != 0) {
// IF - for not null values
if (sheet.getRow(i).getCell(j) != null) {
Cell cell = sheet.getRow(i).getCell(j);
int cellType = cell.getCachedFormulaResultType();
if(cellType==Cell.CELL_TYPE_NUMERIC){
System.out.println(cell.getNumericCellValue()+" "+cell.getCachedFormulaResultType());
}else if(cellType==Cell.CELL_TYPE_STRING){
System.out.println(cell.getRichStringCellValue()+" "+cell.getCachedFormulaResultType());
}
} else {
cellData[i][j] = "";
}
} else {
continue;
}
//System.out.println(cellData[i][j]);
}
}
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
//System.out.print(cellData[i][j] + " ");
dataProviderArray[i - 1][j] = cellData[i][j];
}
}
workbook.close();
return dataProviderArray;
}}
所有这些值都是根据公式计算的缓存值。
除日期外,所有值都按预期获得,它来自42887.0 而不是Jun-2017 基本上所有值都不是excel单元格中的单独值,而是从公式计算的值,因为日期POI返回其类型为CELL_TYPE_NUMERIC ,不明白如何处理这个问题,因为无法使用 POI 的DataFormat,因为我要读取的所有值都作为公式?
【问题讨论】:
-
您想要 Excel 中显示的值还是其他内容?
标签: java excel-formula apache-poi