【发布时间】:2018-05-22 17:56:45
【问题描述】:
我必须为一个学校项目开一个测试日期。此 testdate 是一个包含数字、字母、日期和时间的 excel(xlsx) 文件。但使用下面的代码读取 excel 文件,但我得到奇怪的数字,如 42538.0 和 1.153481443E9。日期之后。
public class Page4_Controller implements Initializable {
@FXML
private Button button1;
public void Button1Action(ActionEvent event) throws IOException {
//Initialize excel file
FileChooser fc = new FileChooser();
fc.getExtensionFilters().addAll(
new ExtensionFilter("Excel Files", "*.xlsx"));
File selectedFile = fc.showOpenDialog(null);
// Read file
readXLSXFile(selectedFile.getAbsolutePath());
}
public static void readXLSXFile(String excelFilePath) throws IOException {
FileInputStream fys = new FileInputStream(new File(excelFilePath));
//Create workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fys);
//Create a sheet object to retrive the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//That is for evalueate the cell type
FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
DataFormatter df = new DataFormatter();
//Default data for database (comes later)
//String airport = sheet.getRow(1).getCell(1).getStringCellValue();
//Date date = sheet.getRow(2).getCell(1).getDateCellValue();
for (Row row : sheet) {
for (Cell cell : row) {
switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
//If cell is a numeric format
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
System.out.print(df.formatCellValue(cell) + "\t");
break;
//If cell is a string format
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getRichStringCellValue() + "\t");
break;
}
}
System.out.println();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
【问题讨论】:
-
42538.0 可能是一个日期 (2016-06-17 00:00)。您需要检查单元格类型是否为 DATE,如果是则进行相应处理。
-
日期是这样写的:Date Found: 17-Jun-2016,cell type是date。
标签: java excel date apache-poi xlsx