英文:
Parsing Excel in Java - index out of bounds
问题
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 = Integer.valueOf(Price);
if (priceValue != null && (priceValue < 80 || priceValue > 130)) {
flag = true;
}
}
}
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(flag);
return flag;
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Expected Output: (Based on the provided spreadsheet)
True
英文:
I am trying to read an Excel file but I cant seem to get my code to work. The error it returns has to with Array out of bounds, but whatever number It doesnt work. Any clue where my code is incorrect?
Notes: Trying to read only the Price column and make sure the values are not NULL, N/A, less than 80 and greater than 130.
SpreadSheet:
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;
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
Expected Output: (Based on spreadsheet provided)
True
答案1
得分: 1
按照评论中的说明,您应该使用一个库,以POI为例,因为很可能您从Excel中的工作表数量中获得了错误。
英文:
As stated in the comments, you should use a library, POI being an example, because most probably you get the error from the number of sheets in the excel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论