Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 错误:";无法从数字单元格中获取字符串值";,转换Excel时_Java_Excel - Fatal编程技术网

Java 错误:";无法从数字单元格中获取字符串值";,转换Excel时

Java 错误:";无法从数字单元格中获取字符串值";,转换Excel时,java,excel,Java,Excel,我有带日期列的excel工作表,当我运行程序时,我遇到以下错误: Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell 我运行的代码: String date =sheets.getRow(choosenRow).getCell(3).getStringCellValue().toString(); 如何将数值转

我有带日期列的excel工作表,当我运行程序时,我遇到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell
我运行的代码:

String date =sheets.getRow(choosenRow).getCell(3).getStringCellValue().toString();

如何将数值转换为字符串?在我的例子中,我使用了
.toString()
但似乎不起作用。

我认为这是因为您使用的是
.getStringCellValue()
,而您应该使用
getNumericCellValue()
.getStringCellValue()
不能与数字单元格一起使用。顺便说一下,我假设您正在使用ApachePOI

有关更多信息,请参阅


我不知道为什么我被否决了,你能在评论中告诉我如何重写它以使其更清楚(如果这是问题)或告诉我它是怎么错的吗?

我没有测试你的代码

但是

您应该尝试
Object
class从该exal文件获取数据。如果成功接收数据。然后可以将转换为日期或字符串

比如:

Object objdata = sheets.getRow(choosenRow).getCell(3).getStringCellValue();

该错误告诉您,如果单元格类型为
NUMERIC
,则可以使用适当的方法
getNumericCellValue()


如果您以前不知道该类型,并且需要读取一些值,则可以对该类型(
getCellType()
)执行
开关
,并从该枚举的结果中使用正确的方法

特别是对于数字类型,您可以检查日期元素:

public String getContent(Cell c){
    switch(c.getCellType()){
        case: NONE     :  throw new IllegalArgumentException("NONE");
        case: BLANK    :  return "";
        case: BOOLEAN  :  return ""+c.getBooleanCellValue();
        case: ERROR    :  return ""+c.getErrorCellValue()
        case: FORMULA  :  return c.getCellFormula()
        case: NUMERIC  :  return HSSFDateUtil.isCellDateFormatted(c)) ? 
                                 c.getDateCellValue()) : ""+c.getNumericCellValue();
        case: STRING   :  return c.getStringCellValue()
}

参考

谢谢大家,它现在工作得很好。我已将代码更改为:

Date date =sheets.getRow(choosenRow).getCell(3)getDateCellValue();
dateTextField.setText(""+date);

号码的类型是什么?双人房?还是int?:“对于数值单元格,我们抛出一个异常。”。使用
getNumericCellValue()
,然后将
double
转换为Excel中的
String
@PieterMantel。格式较短date@VinceEmigh没有work@mona您必须提供更多的上下文,例如正在使用的工作表。该错误表示您的单元格是数字单元格。如果您建议单元格是日期值,可以尝试
getDateCellValue()
Date date =sheets.getRow(choosenRow).getCell(3)getDateCellValue();
dateTextField.setText(""+date);