首页 > 解决方案 > 使用 Java Apache POI 更新 Excel 文件中的单元格

问题描述

我正在尝试使用 Java(Apache POI)更新现有 excel 文件中的空单元格,这是我编写的代码,我没有收到任何错误,并且值也没有更改。

        FileInputStream file = new FileInputStream(new File("recap.xlsx"));
        
 
        
        XSSFWorkbook workbook = new XSSFWorkbook(file);
         
        
         XSSFSheet sheet = workbook.getSheetAt(0);
         Cell cell = null;
         
       //Retrieve the row and check for null
         XSSFRow sheetrow = sheet.getRow(7);
         if(sheetrow == null){
             sheetrow = sheet.createRow(7);
             System.out.println("its null 1 ");
         }
         //Update the value of cell
         cell = sheetrow.getCell(7);
         if(cell == null){
             cell = sheetrow.createCell(7);
             System.out.println("its null  2 !");
         }
         
         
         cell.setCellValue("Second");

     file.close();

     workbook.close();

我在控制台中得到“它的 null 2!”。

有什么解决办法吗?

谢谢 :)

标签: javaexcelapache-poi

解决方案


您需要打开一个输出流并写入工作簿,如下所示:

file.close();

FileOutputStream outputStream = new FileOutputStream("recap.xlsx");
workbook.write(outputStream);

workbook.close();
outputStream.close();

此外,请确保在此写入操作后关闭工作簿和输出流。


推荐阅读