2012-03-03 164 views
0

我正在使用Apache poi api for java來寫入Excel工作簿中的現有工作表。我的問題是,在我嘗試編輯的工作表中,如果行中的任何單元格不爲空(即其中包含某種類型的值),那麼程序將正常運行並編輯該行中的任何特定單元。例如,如果我的工作表(1,1)中的單元格包含一個值,那麼程序將不會編輯同一行的其他單元格(1,5)或(1,12)等等。但是,如果我的整行是空的,即所有單元格都包含null,那麼代碼將拋出一個空指針異常,我無法弄清楚如何刪除。這裏是我用於寫我的excel類中的特定單元格的項目的寫入方法。使用apache poi api在excel中修改工作表的問題

public void write(int row, int column, String label) { 


    try { 
     InputStream inp = new FileInputStream(filePath); 
     Workbook wb = WorkbookFactory.create(inp); 
     Sheet sheet = wb.getSheetAt(0); 
     Row sheetRow = sheet.getRow(row); 
     Cell cell = sheetRow.getCell(column); 
     //String cellContents = cell.getStringCellValue(); 
     //  //Modify the cellContents here 
     //  // Write the output to a file 
     if (cell == null) { 
      cell = sheetRow.createCell(column); 
      cell.setCellType(Cell.CELL_TYPE_STRING); 
     } 
     cell.setCellType(Cell.CELL_TYPE_STRING); 
     cell.setCellValue(label); 
     FileOutputStream fileOut = new FileOutputStream(filePath); 
     wb.write(fileOut); 
     fileOut.close(); 
    } catch (IOException ex) { 
     Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (InvalidFormatException ex) { 
     Logger.getLogger(ExcelManipulator.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

是java的拋出關於在非觸摸即空行編輯單元格的例外是:

Exception in thread "main" java.lang.NullPointerException 
at seleniumtest.ExcelManipulator.write(ExcelManipulator.java:76) 
at seleniumtest.SeleniumTest.main(SeleniumTest.java:28) 

Java結果:1

任何人可以幫助我擺脫這使我的代碼也寫了一個單元,即使整行是空的?謝謝

回答

3

我不知道NPE究竟在哪裏拋出,但我很肯定ExcelManipulator.java的第76行是這樣的:Cell cell = sheetRow.getCell(column);

API for Sheet所述,如果您要求未定義的行,則會得到空值 - 如果整行爲空,則爲空。

所以你可以在上面提到的行之前插入if(sheetRow == null){sheetRow = sheet.createRow(row);},你應該沒問題。

+0

哦,是的,這解決了這個問題。非常感謝:) – pslayer89 2012-03-04 01:28:13

+0

Thx。我有同樣的問題。真的很方便的答案。 :-) – Juraj 2013-07-10 11:02:12