Java 错误:";无法从数字单元格中获取字符串值";,转换Excel时
我有带日期列的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(); 如何将数值转
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);