繁体   English   中英

使用Apache POI(java)将excel单元存储在二维数组中。 尽管我将所有Excel单元格设置为“文本”格式,但仍返回异常

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

我对使用Apache POI极为陌生(事实上,对Java来说也是新手),并且遇到了一个我无法确定如何解决的异常。

显然,您不能在数组中存储2种不同的数据类型,因此我选择了每列数据,并将单元格格式转换为Excel中的“文本”。

然后,我尝试使用以下命令将此数据存储在数组中:

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)");
                }
            }
        }
    }
}

这样的输出是“单元格数据不是字符串(文本)”的无数行,我在这里哪里出错了? 请原谅我的疏忽,我也是Stackoverflow的新手,也想在这里成为社区的重要成员:)感谢您的建议!

编辑:根据要求添加了e.printStackTrace()。

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)

有趣的是,当我将其从cell.getStringCellValue()更改为cell.getNumericCellValue()时,IllegalStateException然后更改为“无法从文本单元格获取数值” ...尽管该单元格已转换为文本,但我认为还是Excel文档实际不是更改为字符串数据并将其作为其固有数据类型传递的吗? 再次感谢

似乎有些单元格是数字类型的,而有些则是字符串类型的。 您需要分别处理数字单元格类型和字符串单元格类型。 我还没有检查一下,但是可以确定...以下方法可以工作。

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
}    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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