使用Apache POI在Excel中的单元格中读取问题 [英] Issue reading in a cell from Excel with Apache POI

查看:134
本文介绍了使用Apache POI在Excel中的单元格中读取问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Apache POI读取旧的(2007年前和XLS之前)Excel文件.我的程序转到行的末尾并进行迭代,直到找到不为null或为空的值.然后迭代几次,然后获取这些单元格.该程序可以很好地读取Office 2010中制作的XLSX和XLS文件.

I am trying to use Apache POI to read in old (pre-2007 and XLS) Excel files. My program goes to the end of the rows and iterates back up until it finds something that's not either null or empty. Then it iterates back up a few times and grabs those cells. This program works just fine reading in XLSX and XLS files made in Office 2010.

我收到以下错误消息:

Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)

在线:

num = Double.parseDouble(str);

来自代码:

str = cell.toString();

if (str != "" || str != null) {
    System.out.println("Cell is a string");
    num = Double.parseDouble(str);
} else {
    System.out.println("Cell is numeric.");
    num = cell.getNumericCellValue();
}

其中,cell是文档中的最后一个不为空或为null的单元格.当我尝试打印不为空或为null的第一个单元格时,它不打印任何内容,因此我认为我无法正确访问它.

where the cell is the last cell in the document that's not empty or null. When I try to print the first cell that's not empty or null, it prints nothing, so I think I'm not accessing it correctly.

推荐答案

最好评估单元格的类型,然后执行所需的操作.我使用以下代码来处理单元格数据(检查我是否还处理了空白单元格):

It would be better to evaluate the cell type and then do what you need. I use this code to handle the cell data (check that I even handle blank cells):

switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
        str = cell.toString().trim();
        break;
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
            //you should change this to your application date format
            objSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
            str = objSimpleDateFormat.format(cell.getDateCellValue());
        } else {
            num = cell.getNumericCellValue();
            str = String.valueOf(cell.getNumericCellValue());
        }
        break;
    case Cell.CELL_TYPE_BLANK:
        str = "";
        break;
    case Cell.CELL_TYPE_ERROR:
        str = "";
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        str = String.valueOf(cell.getBooleanCellValue());
    break;
}

这篇关于使用Apache POI在Excel中的单元格中读取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆