简体   繁体   中英

Using Apache POI (java) to store excel cells in 2 dimensional array. Exception being returned despite me formatting all Excel cells as “text”

I am extremely new to using Apache POI (and still new to Java too, infact!) and have come across an exception that I cannot determine how to fix.

Obviously you cannot store 2 different datatypes in an array, so I selected every column with data and converted the cell format to "Text" in Excel.

I then try to store this data in an array with the following:

String cellData[][] = new String[rows][cols];            
System.out.println(rows+" entries found with "+cols+" columns of data");

//iterate over every row and store cell data;
for(int i=0; i<rows; i++){
    row = worksheet.getRow(i);
    if(row != null){
        for(int j=0;j<cols;j++){
            cell = row.getCell(j);
            if(cell != null){
                try{
                    cellData[i][j] = cell.getStringCellValue();
                }catch(IllegalStateException e){
                    System.out.println("Cell data is not a string(text)");
                }
            }
        }
    }
}

The output from this is countless rows of "Cell data is not a string(text)", where am I going wrong here? Forgive me for any oversights I am also new to Stackoverflow and want to become a valued member of the community here too :) Thanks for your advice!

EDIT: Added e.printStackTrace() as requested.

at exceltesting.ExcelTesting.main(ExcelTesting.java:80)
java.lang.IllegalStateException: Cannot get a text value from a numeric cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:648)
at org.apache.poi.hssf.usermodel.HSSFCell.getRichStringCellValue(HSSFCell.java:725)
at org.apache.poi.hssf.usermodel.HSSFCell.getStringCellValue(HSSFCell.java:708)

Interestingly enough, when I change it from cell.getStringCellValue() to cell.getNumericCellValue() the IllegalStateException then changes to "Cannot get a numerical value from a text cell"... I think the excel document, despite converting the cells to text is not actually changing to string data and passing them as their inherent data type? Thanks again

It seems that some of the cells are of Numeric type and some of them are of String Type. You need to handle Numeric Cell Types and String Cell types separately. I have not checked on my end, but sure... the following will work.

Cell cell = row.getCell(j); 
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
    case Cell.CELL_TYPE_NUMERIC:
    cellData[i][j] = String.valueOf(cellValue.getNumberValue());
    break;
    case Cell.CELL_TYPE_STRING:
    cellData[i][j] = cell.getStringCellValue();
    break
}    

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