嗨,我們一直在閱讀xls和xlsx文件使用Apache poi我們的Java程序,問題是我們得到空指針異常有兩個原因。第一個是我們已經是空白單元格解決了,另一個是當我們選擇某個沒有任何記錄的列時。空指針異常apache poi
我們的程序詢問excel文件的路徑,然後查看文件的具體圖紙編號和你想讀..這裏的片是用於讀取xls文件的代碼
public void readXLSFile()throws IOException{
InputStream ExcelFileToRead = new FileInputStream(path);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(sheetname);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
list1.clear();
while (rows.hasNext())
{
headers.clear();
row=(HSSFRow) rows.next();
// Iterator cells = row.cellIterator();
headers.add("contents");
cnt = cnt+1;
cell = row.getCell(cols);
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//System.out.println(cell.getStringCellValue()+"(string)");
list.add(cell.getStringCellValue());
d.add(cell.getStringCellValue());
list1.add(new KeyValuePair(cell.getStringCellValue(),""));
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
//System.out.println(cell.getNumericCellValue()+"(numeric)");
double num = cell.getNumericCellValue();
String num2 = String.valueOf(num);
list.add(num2);
d.add(num2);
list1.add(new KeyValuePair(num2,""));
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN)
{
//System.out.println(cell.getBooleanCellValue()+"(boolean)");
String bool = String.valueOf(cell.getBooleanCellValue());
list.add(bool);
d.add(bool);
list1.add(new KeyValuePair(bool,""));
}
else
{
//U Can Handel Boolean, Formula, Errors
}
//System.out.println();
}
arrey = list.toArray(new String[list.size()]);
data.add(d);
// System.out.println(data);
model = new DefaultTableModel();
table_1.setModel(model);
table_1.setModel(model);
model.setColumnIdentifiers(new String[] {"row","contents"});
for (KeyValuePair p : list1){
int nor=table_1.getRowCount();
int n2 = nor +1;
n1 = Integer.toString(n2);
// model.addColumn(new String [] {n1});
model.addRow(new String[] {n1,p.key, p.value});
}
// model.addColumn(new String[] {n1});
}
變量SHEETNAME是Excel文件的表NUM BER
HSSFSheet sheet=wb.getSheetAt(sheetname);
和變量的cols是爲特定的列你想讀
cell = row.getCell(cols);
我們可以讀到每個表的第一列,並在第二頁第二欄,但是當我編輯我現在測試文件的程序只能讀取每片..錯誤的第一列是空指針exception..wish你能幫助在此先感謝
可以打印異常的堆棧跟蹤。如果我們能夠知道哪個語句實際上引起了異常,我會幫助的。 –
它有點令人困惑...你正在使用'sheetname',它似乎是一個帶有'HSSFSheet sheet = wb.getSheetAt(sheetname);'的字符串。 'getSheetAt'始終接受圖紙索引的數值。請確認。 – Sankumarsingh
這是唯一的錯誤,我得到 java.lang.NullPointerException 順便說一句,我圍繞在上面提到的方法在try catch .. –