0

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();
4

1 回答 1

0

如果现有 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!
}
于 2021-01-29T11:43:25.200 回答