我一直在嘗試讀取Excel表格並將單元格中的數據插入到程序中。我很成功,但是當我嘗試從位置4及以後的單元格獲取數據時,我遇到了一個越界異常。不知道爲什麼會這樣,因爲我可以稱呼位置0,1,2和3就好。這是我的代碼。嘗試讀取單元格時發生奇怪的越界異常
public void readExcel(File file) {
try {
//Workbook newBook = new Workbook();
Workbook workbook = Workbook.getWorkbook(file);
WritableWorkbook workbookOutput = Workbook.createWorkbook(new File("output.xls"));
// Workbook workbook = Workbook.getWorkbook(new File(「Res.xls」));
WritableSheet sheetOutput = workbookOutput.createSheet("First Sheet", 0);
sheet = workbook.getSheet(0);
boolean isnotnull = true;
int i = 0;
while(isnotnull){
//Cell a1 = sheet.getCell(0, 2);
try{
Cell a2 = sheet.getCell(0, i);
Cell a3 = sheet.getCell(1, i);
Cell a4 = sheet.getCell(2, i);
stringa1 = a2.getContents();
stringa2 = a3.getContents();
stringa3 = a4.getContents();
char c = stringa2.charAt(0);
char d = stringa2.charAt(1);
if(Character.isDigit(c) || Character.isDigit(d)){
System.out.println("found one");
stringa1 = stringa1 + "" + stringa2;
stringa2 = stringa3;
Cell a5 = sheet.getCell(3, i);
try{
Cell a10 = sheet.getCell(4, i);
// System.out.print("Cell" + a6.getContents());
}
catch(Exception e){
System.out.println(e);
}
stringa4 = a5.getContents();
stringa3 = stringa4;
// checkCells(1, i);
}
Label label = new Label(0, i, stringa1);
Label label2 = new Label(1, i, stringa2);
Label label3 = new Label(2, i, stringa3);
sheetOutput.addCell(label);
sheetOutput.addCell(label2);
sheetOutput.addCell(label3);
i++;
System.out.println(stringa1 + " |||||||||||| " + stringa2 + " |||||||| " + stringa3 + " " + i);
}catch(Exception e){
System.out.println(e);
isnotnull = false;
}
}
workbookOutput.write();
try{
workbookOutput.close();
}catch(Exception r){
System.out.println(r);
}
System.out.println(stringa1);
workbook.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}`enter code here`
我認爲[這是一個類似的問題](http://stackoverflow.com/questions/14953363/writing-excel-data-to-database-in-java/14953416#14953416)。如果一行在4個單元格之後結束,則第5個單元格不存在於包含行單元格的(array support!)列表中。所以你試圖獲得4長陣列中的第5個元素:OutOfBounds異常。您總是必須測試列表是否足夠長,以便在嘗試獲取該元素之前獲得該元素... – ppeterka 2013-02-22 11:48:29
我能做些什麼來獲得此元素嗎? – 2013-02-22 11:55:11