Apache POI:excel文件中的内容被破坏

问题描述 投票:1回答:1

我正在编写一个写入Excel文件的方法。在调用之前,我创建了一个工作簿和一个工作表。代码执行时没有任何错误,但是当打开创建的Excel文件时,我收到消息:我们发现某些内容存在问题...

我的方法看起来像这样:

public void writeToCell(int rowNumber, int cellNumber, Double content) {
    Row row = sheet.createRow(rowNumber);
    Cell cell = row.createCell(cellNumber);

    cell.setCellValue(content);

    try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx", true)) {
        workbook.write(outputStream);
        outputStream.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这就是我调用方法的方法:

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(month);

writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);
java excel apache-poi
1个回答
1
投票

您不应该明确地将数据附加到Excel工作簿,这也是@Axel在他的评论中指出的

try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx", true)) 

代替

try (FileOutputStream outputStream = new FileOutputStream(month + ".xlsx")) 

对于旁注,

writeToCell(25, 4, 0.0);
writeToCell(25, 6, 23.32);  

writeToCell的最后一次调用将覆盖相同第25行的先前值。因为,你在每个电话中创建新的Row

Row row = sheet.createRow(rowNumber);
© www.soinside.com 2019 - 2024. All rights reserved.