我正在使用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
任何人可以帮助我摆脱这使我的代码也写了一个单元,即使整行是空的?谢谢
哦,是的,这解决了这个问题。非常感谢:) – pslayer89 2012-03-04 01:28:13
Thx。我有同样的问题。真的很方便的答案。 :-) – Juraj 2013-07-10 11:02:12