我有XLSXXLSM文件,其中包含一些预定义的宏。我尝试使用Apache POI编辑这些文件,但是宏会自动删除。当我尝试在修改后打开文件时,出现一个通知窗口,该文件被删除,因为文件已损坏:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <logFileName>error066080_01.xml</logFileName>
    <summary>Error in file (C:\_privat\completeReport.xlsm)</summary>
    <removedRecords>
        <removedRecord>/xl/worksheets/sheet1.xml</removedRecord>
        <removedRecord>/xl/calcChain.xml</removedRecord>
    </removedRecords>
</recoveryLog>


我使用以下代码来处理文件,Vars.XLS包含XLSX/XLSM文件的路径。

File file = new File(Vars.XLS);
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook workbook = XSSFWorkbookFactory.createWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.createRow(recordcount+4);
Cell cell;

cell = row.createCell(0);
cell.setCellValue(recordcount);

inputStream.close();
FileOutputStream fileOut=new FileOutputStream(Vars.XLS);
workbook.write(fileOut);
fileOut.close();

最佳答案

您正在尝试更新Excel工作表。如果更新,则不应创建行或单元格,而必须读取单元格。我在下面提供了简短的代码段,您可以尝试。

XSSFRow row = sheet.getRow(some number);
Cell cell = row.getCell(some number);
cell.setCellValue(recordcount);

09-12 09:22