简体   繁体   中英

Error: "Cannot get a STRING value from a NUMERIC cell", when converting Excel

I have excel sheet with date column, when I run my program I got this error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell

My code that I run:

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

How can I convert numeric value to String? in my case I used .toString(); but seems it didn't worked.

I believe that it is because you are using .getStringCellValue() , when you should be using getNumericCellValue() . .getStringCellValue() can't be used with NUMERIC cells. I'm assuming that you are using Apache POI by the way.

See https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html for more info.

I'm not sure why I was downvoted, can you let me know in the comments about how I can rewrite it to be more clear(if that is the problem) or tell me how it is wrong?

i not tested your code..!

but

you should try Object class to get data from that exal file. if data are successfully recevied. then you can convert in to date or String.

like :

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

Thanks all, it's working perfectly now. I have changed the code to be like that:

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

The error tells you that the cell if type NUMERIC , you may use the approriate method getNumericCellValue()

String date = "" + sheets.getRow(choosenRow).getCell(3).getNumericCellValue();

If you don't know the type before, and need to read some values, you may implment a switch on the type ( getCellType() ) and from the result of this enum use the right method

Specifically for the numeric type, you can check for date element :

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

Ref to How to read Excel cell having Date with Apache POI?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM