java - 从 Excel 导入空日期

标签 java excel apache-poi

我有一个 Excel 工作表,我从中读取 Excel cel 值并导入到数据库

使用 Apache POI:

 if (row.getCell(8) != null) {
          setActualDeparture(DateUtil.getJavaDate(row.getCell(8).getNumericCellValue()));
   }

Excel 工作表在单元格 8 上为空,因此不应导入任何内容。但它需要像 1899-12-31T00:00:00 这样的日期

可能是什么问题?

最佳答案

如果文件中没有为此单元格存储任何内容,则 Row.getCell(int cellnum) 仅返回 NULL。如果文件中存储了该单元格的内容,它将返回该单元格。即使这只是一个 NumberFormat 或此单元格的任何其他信息。

但是还有第二种方法Row.getCell(int cellnum, Row.MissingCellPolicy policy) http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell%28int,%20org.apache.poi.ss.usermodel.Row.MissingCellPolicy%29可以在您的情况下使用。

示例: enter image description here

A1 中没有任何内容,但有一个特殊的 NumberFormat 且不通用。

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

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

class GetEmtyCellTest {

 public static void main(String[] args) {
  try {

   InputStream inp = new FileInputStream("workbook.xlsx");
   Workbook wb = WorkbookFactory.create(inp);

   Sheet sheet = wb.getSheetAt(0);

   Row row = sheet.getRow(0);

   System.out.println(row.getCell(0).getNumericCellValue()); //0.0
   System.out.println(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //null


   FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
   wb.write(fileOut);
   fileOut.flush();
   fileOut.close();

  } catch (InvalidFormatException ifex) {
  } catch (FileNotFoundException fnfex) {
  } catch (IOException ioex) {
  }
 }
}

关于java - 从 Excel 导入空日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986962/

相关文章:

java - 无需额外命令即可删除尾随零

vba - 附加到分隔的文本文件

java - 如何在 Java 中找到 MS Word 文档的页面大小、页面高度和宽度?

java - 在新的 Excel 工作表中写入行

java - 禁止在 JTabbedPane 中更改选项卡

java - Netty:停止重新连接并关闭

vba - 在外语版本的 Excel 中从 vba 调用工作表函数

java - Apache POI for excel 获取依赖单元格

java - Spring boot - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN'

vba - 如何屏蔽excel宏代码