无法使用 Apache POI 在 Excel 中写入空行

问题描述

Excel 格式 - .xls

我正在尝试将值从一个 Excel 工作表复制/粘贴到另一个现有的 Excel 工作表。我无法在空行中写入值。如果 Excel 行有一些值,则它正在更新。请检查下面的代码

我的代码

FileInputStream file = new FileInputStream(new File(strWorkBookName));
hssfWorkbook strWorkBook = new hssfWorkbook(file);
hssfSheet sheet = strWorkBook.getSheet(sheetName);

// Retrieve the row and check for null
hssfRow sheetrow = sheet.getRow(rowNo);
if(sheetrow == null){
    logger.info("CREATING ROW"+rowNo);
    sheetrow = sheet.createRow(rowNo);
}
// Update the value of a cell
hssfCell cell = sheetrow.getCell(columnNo);

if(cell == null){
    logger.info("CREATING COLUMN " + columnNo);
    cell = sheetrow.createCell(columnNo); }

cell.setCellValue(valuetoUpdate);

FileOutputStream outFile = new FileOutputStream(new File(strWorkBookName));
strWorkBook.write(outFile);
outFile.close();

解决方法

您确定您正在正确验证现有 Excel 文件是否正在更新?

您忘记关闭 Workbook 对象,但您的代码对我来说仍然像魅力一样工作。这是我测试过的工作代码(适用于完整行和空行):

public static void main(String[] args) throws IOException {

    int sheetPosition = 0;
    int rowPosition = 100;
    int cellPosition = 100;
    String excelFilePath = "D:\\Desktop\\testExcel.xls";

    FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
    HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
    HSSFSheet sheet = workbook.getSheetAt(sheetPosition);

    HSSFRow sheetrow = sheet.getRow(rowPosition);
    if (sheetrow == null){
       System.out.println("new row at position " + rowPosition);
       sheetrow = sheet.createRow(rowPosition);
    }

    HSSFCell cell = sheetrow.getCell(cellPosition);
    if(cell == null){
        System.out.println("new cell (for row " + rowPosition + ") at position " + cellPosition);
        cell = sheetrow.createCell(cellPosition);
    }

    cell.setCellValue("New Amazing Value!");

    FileOutputStream outFile = new FileOutputStream(new File(excelFilePath));
    workbook.write(outFile);
    outFile.close();
    workbook.close(); // <-- Do not forget that!
}