[英]Error: "Cannot get a STRING value from a NUMERIC cell", when converting 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();
如何将数值转换为字符串? 就我而言,我使用了.toString();
但似乎没有用。
我相信这是因为您正在使用.getStringCellValue()
,而您应该使用getNumericCellValue()
。 .getStringCellValue()
不能与 NUMERIC 单元格一起使用。 顺便说一下,我假设您正在使用 Apache POI。
有关更多信息,请参阅https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html 。
我不确定为什么我被否决了,您能否在评论中告诉我如何重写它以使其更清晰(如果这是问题)或告诉我它是如何错误的?
我没有测试你的代码..!
但
您应该尝试Object
类从该 exal 文件中获取数据。 如果数据成功接收。 然后您可以转换为日期或字符串。
喜欢 :
Object objdata = sheets.getRow(choosenRow).getCell(3).getStringCellValue();
谢谢大家,它现在工作得很好。 我已将代码更改为如下所示:
Date date =sheets.getRow(choosenRow).getCell(3)getDateCellValue();
dateTextField.setText(""+date);
该错误告诉您,如果单元格类型为NUMERIC
,您可以使用适当的方法getNumericCellValue()
String date = "" + sheets.getRow(choosenRow).getCell(3).getNumericCellValue();
如果您之前不知道类型,并且需要读取一些值,您可以在类型( getCellType()
)上实现一个switch
,并从这个枚举的结果中使用正确的方法
特别是对于数字类型,您可以检查日期元素:
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.