Java – 无法在Excel单元格中写入

FileInputStream file = new FileInputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheet("Sheet1"); Cell name_c = null; Cell department_c = null; Cell prev_depart_c = null; HSSFRow row = sheet.createRow((short) 0); HSSFCellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); department_c = sheet.getRow(2).getCell(1); // throws exception here department_c.setCellValue(department); prev_depart_c = sheet.getRow(3).getCell(1); prev_depart_c.setCellValue(prev_depart); emp_no_c = sheet.getRow(4).getCell(1); emp_no_c.setCellValue(emp_no); file.close(); FileOutputStream outFile =new FileOutputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output10.xls")); workbook.write(outFile); outFile.close(); 

我试图写现有的Excel文件,但它抛出我在评论区域java.lang.NullPointerException 。 任何意见或build议,高度赞赏。

在你的代码中,这一行HSSFRow row = sheet.createRow((short) 0); 只是在位置0创build一个新的行。 除此之外的任何东西仍然是null ,因此当您尝试调用任何方法时将抛出一个NPE。

为了能够连续写入单元格,您需要先在特定位置创build一行。

 HSSFRow row = sheet.createRow(2); // create a row at rownum 2 // use the created row and add/edit cells in it. 

顺便说一句,您在文件path中使用冗余斜线

 File("//Users//"+ usr +"//Desktop//TNA//output//output.xls")); 

一个斜线就足够了。 斜杠(/)不必像反斜杠那样在string中转义。

如果单元格不在工作表上,则需要创build它们:

 public class ExcelExample { public static void main(String[] args) throws IOException { FileInputStream file = new FileInputStream(new File("/output.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheet("Sheet1"); Cell name_c = null; Cell department_c = null; Cell prev_depart_c = null; HSSFRow row = sheet.createRow((short) 0); HSSFCellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); HSSFRow row2 = sheet.createRow(2); HSSFCell cell = row2.createCell(1); cell.setCellValue("5"); HSSFRow row3 = sheet.createRow(3); HSSFCell cell2 = row2.createCell(1); cell2.setCellValue("5"); file.close(); FileOutputStream outFile =new FileOutputStream(new File("/output10.xls")); workbook.write(outFile); outFile.close(); } }