【问题标题】:Parsing Excel in Java - index out of bounds在 Java 中解析 Excel - 索引超出范围
【发布时间】:2020-12-23 09:53:37
【问题描述】:

我正在尝试读取 Excel 文件,但我的代码似乎无法正常工作。它返回的错误必须与 Array 超出范围有关,但无论数字如何它都不起作用。任何线索我的代码不正确?

注意:尝试仅读取 Price 列并确保值不为 NULL、N/A、小于 80 且大于 130。

电子表格:

boolean flag = true; 
File inputF = new File("data.xlsx")
InputStream getStream = new FileInputStream(inputF);

try{
    if(getStream.read() != -1){
    BufferedReader reader = new BufferedReader(new InputStreamReader(getStream));
    String line;

    while((line = reader.readLine()) != null){
        String[] csvs = line.split(",");
        for (String str : csvs){
            if (str != null && (str.equals("NA") || str.length() == 0)) {
                System.out.println(str);
                flag = false;
                break;
            }
        }
        if (!flag){
            break;
        }else{
            String Price = csvs[1]; //TODO replace with price index 
            price = price.trim();
            Integer priceValue = new Integer(Price);
            if (priceValue != null && (priceValue < 80 || priceValue > 130)){
                flag = true;
            }
        }
    }
    reader.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(flag);
return flag;

错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 

预期输出:(基于提供的电子表格)

True 

【问题讨论】:

  • xlsx 文件不是纯文本文件(如csv),您无法使用BufferedReader 读取其行。你必须使用一个库,比如Apache POI。如果您不相信,请将其文件扩展名从 .xlsx 更改为 .zip 并打开生成的存档。您会在其中找到不同的文件和文件夹。

标签: java arrays inputstream bufferedreader bufferedinputstream


【解决方案1】:

如 cmets 所述,您应该使用库 POI being an example,因为您很可能会从 excel 中的工作表数中得到错误。

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多