【问题标题】:Importing null date from Excel从 Excel 导入空日期
【发布时间】:2014-11-18 05:06:28
【问题描述】:

我有一张 excel 表,我正在读取 excel cel 值并导入数据库

使用 Apache POI:

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

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

可能是什么问题?

【问题讨论】:

  • 单元格 8 是该行中的第 9 个单元格。这有什么改变吗?
  • 是的,这并没有改变任何东西..
  • 请注意:此 excel 工作表是使用 java 脚本创建的。
  • 如果 cell(8) 为 null,您将通过 getNumericCellValue() 调用获得 NullPointerException。显然,它不为空。打开 Excel 电子表格。你看到里面有数据吗?
  • 已打开且为空(空白)(空格)

标签: java excel apache-poi


【解决方案1】:

如果该单元格的文件中没有存储任何内容,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可以在你的情况下使用。

示例:

A1 中没有任何内容,但有一个特殊的 NumberFormat 并且没有应用 General。

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) {
  }
 }
}

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 2015-04-03
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多