使用 apache poi 获取 excel 中的所有列记录,而不是仅获取最后一列记录

get all column records in excel instead of getting only last column record using apache poi

我正在尝试使用 apache poi 获取 excel 中的所有列记录。但我只得到 excel 中的最后一列数据。 下面是我的代码。在下面的代码中,我试图在达到特定列数时创建新行。并在每一行中放置所有列数据。

public static ByteArrayInputStream export(List<String> records) {
  int TOTAL_COLUMN = 8;
  ByteArrayInputStream output = null;
  XSSFWorkbook workbook = null;
  InputStream inputStream = null;
  try (ByteArrayOutputStream excelFileStream = new ByteArrayOutputStream();) {
     inputStream =
           new ClassPathResource(TEMPLATE_PATH).getInputStream();
     workbook = new XSSFWorkbook(inputStream);
     XSSFSheet sheet = workbook.getSheetAt(DATA_SHEET_INDEX);
     XSSFCellStyle evenRowCellStyle = createCellStyle(workbook, EVEN_ROW_CELL_COLOR);
     XSSFCellStyle oddRowCellStyle = createCellStyle(workbook, ODD_ROW_CELL_COLOR);

     Integer rowIndex = STARTING_ROW;
     int numberOfColumn = 0;
     XSSFCellStyle cellStyle = oddRowCellStyle;

     /**
      * Populates row cell details with list data
      */
     int totalColumn = TOTAL_COLUMN;

     for (String data : records) {
        if (numberOfColumn == totalColumn) {
           rowIndex++;
           numberOfColumn = 0;
        }
        cellStyle = (rowIndex % 2 == 0) ? evenRowCellStyle : oddRowCellStyle;
        CellUtil.createCell(sheet.createRow(rowIndex), numberOfColumn, data, cellStyle);
        numberOfColumn++;
     }

     workbook.write(excelFileStream);
     output = new ByteArrayInputStream(excelFileStream.toByteArray());
  } catch (Exception e) {
     output = null;
     log.info("Error occurred while exporting to excel sheet.");
  } finally {
     if (workbook != null) {
        try {
           workbook.close();
        } catch (IOException e) {
           log.error("Error occurred while closing excel.");
        }
     }
     Utils.closeInputStream(inputStream);
  }
  return output;
}

以上代码仅给出每行中的最后一列数据。

在您的代码中,调用 sheet.createRow(rowIndex) 总是会创建一个新的空行。因此,该行中所有以前设置的单元格值都会丢失。

您已经在使用 CellUtil。有 CellUtil.getRow 以下内容:

Get a row from the spreadsheet, and create it if it doesn't exist.

这并不总是会创建一个新的空行。相反,它首先尝试获取该行,并且仅在该行不存在时才创建一个新行,

使用也是如此:

CellUtil.createCell(CellUtil.getRow(rowIndex, sheet), numberOfColumn, data, cellStyle);