我收到以下代码的NullPointerException
。有人可以帮忙解决这个问题吗?我正在尝试将数据库值获取到现有的 Excel 工作表。
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from basicinfo");
FileInputStream fis = new FileInputStream(new File("exceldatabase.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row=spreadsheet.getRow(2);
XSSFCell cell;
cell=row.getCell(2);
cell.setCellValue("user_name");
cell=row.getCell(3);
cell.setCellValue("email");
cell=row.getCell(3);
cell.setCellValue("phonenum");
cell=row.getCell(4);
cell.setCellValue("address");
最佳答案
您需要创建行和单元格对象:
XSSFRow row=spreadsheet.createRow(2);
XSSFCell cell;
cell=row.createCell(2);
cell.setCellValue("user_name");
cell=row.createCell(3);
cell.setCellValue("email");
cell=row.createCell(3);
cell.setCellValue("phonenum");
cell=row.createCell(4);
cell.setCellValue("address");
如果您要打开现有笔记本并且行/单元格/工作表可能存在,则需要如下所示的内容:
Sheet sheet=workbook.getSheet("foo");
if (sheet==null){
sheet=workbook.createSheet("foo");
}
Row row=sheet.getRow(2);
if (row==null){
row=sheet.createRow(2);
}
Cell cell=row.getCell(12);
if (cell==null){
cell=row.createCell(12);
}
cell.setValue("phonenum");
当然,您可能应该创建一些辅助方法,如下所示:
private Sheet getOrCreateSheet(Workbook workbook, String sheetName){
Sheet sheet=workbook.getSheet(sheetName);
if (sheet==null){
sheet=workbook.createSheet(sheetName);
}
return sheet;
}
private Row getOrCreateRow(Sheet sheet, int rowIndex){
Row row=sheet.getRow(rowIndex);
if (row==null){
row=sheet.createRow(rowIndex);
}
return row;
}
private Cell getOrCreateCell(Row row, int colIndex){
Cell cell=row.getCell(colIndex);
if (cell==null){
cell=row.createCell(colIndex);
}
return cell;
}
那么上面的代码就变得更加整洁:
Sheet sheet=getOrCreateSheet(workbook, "foo");
Row row=getOrCreateRow(sheet, 2);
Cell cell=getOrCreateCell(row, 12);
cell.setValue("phonenum");
关于java - XSSF。空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674650/