POI XSSF 覆盖 excel 文件中的特定单元格

POI XSSF overwriting specific cells in excel file

我正在尝试写入现有的 excel 文件。我不想创建新的行或单元格,我只想将数组中的值写到第 x 行第 y 列的值中。到目前为止,每次我尝试这样做时,我只能在创建新行时才能让它工作。请帮忙!!!

      Integer columns = DataImport.columns_in_sheet[0];
        Integer rowNum = learnerRow + 2;

        try {
            FileInputStream inp = new FileInputStream("D:/location/update.xlsx");
            XSSFWorkbook wb = null;
            wb = (XSSFWorkbook) WorkbookFactory.create(inp);
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row = sheet.getRow(18);//places the start row
            XSSFCell cell = null;//places the start column
            cell = row.getCell(0);

//#########################################################################################

//#########################################################################################
            for (int j = 0; j < exportData.length; j++) {
                //sheet.createRow(rowNum+j);
                //row = sheet.getRow(rowNum+j);

                //row = sheet.getRow(rowNum+j);
                for (int i=0; i < columns;i++){

                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(exportData[j][i]);
                }
            }

            // Write the output to a file
            FileOutputStream fileOut = new FileOutputStream("D:/location/update.xlsx");
            wb.write(fileOut);
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

由于行为空,此代码抛出一个空指针,我似乎只能通过创建新行来消除错误。我正在使用 XSSF 格式。

您的代码片段逻辑不清晰。在我看来这不符合逻辑。

但是为了避免 NPE 在使用当前工作表中的行和单元格时,总是需要检查行或单元格是否已经存在或需要重新创建。这是必要的,因为对于不存在的行 Sheet.getRow 将 return null。此外 Row.getCell 将 return null 用于不存在的单元格。

所以我们可以这样做:

Sheet sheet = ...
Row row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx); 
Cell cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);

现在 row 要么是已经存在的行,要么是新创建的行。 cell 要么是一个已经存在的单元格,要么是一个新创建的单元格。 rowcell 都不会是 null。如果 rows/cells 不存在,将在它们被新创建之前得到。所以当前的行和单元格不会被破坏。

循环中同样需要:

Sheet sheet = ...
Row row;
Cell cell;
for (int rowIdx = 0; rowIdx < 10; rowIdx++) {
 row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx);
 for (int cellIdx = 0; cellIdx < 10; cellIdx++) {
  cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);
  // do something with cell
 }
}