添加新单元格会破坏 excel 文件

Appending new cells breaks the excel file

这可能是重复的,因为很多帖子都提到了这类问题,但我找不到这个案例的确切答案。

所以,我有一个 Excel 文件,其中单元格 "E4" 包含一个公式“=C4+D4”。所有其他单元格都是空的,这意味着我无法通过 OpenXml 搜索或获取它们,只是因为它们不存在于 Xml 中。所以为了填充单元格 "C4" 和 "D4" 我必须创建它们(像这样:)

var cell = new Cell(){
    CellReference = new StringValue("C4"),
    DataType = new EnumValue<CellValues>(CellValues.Number),
    CellValue = new CellValue("123")
}

单元格 "D4" 相同,然后将这些单元格附加到行

row.Append(cell);

我打开 excel 文件后显示错误 "Excel found unreadable content in file.xlsx. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes."

我检查过,当 excel 文件中没有公式时,单元格被正确附加。

所以我的问题是,使用 OpenXml 如何在包含公式的 Excel 文件中附加单元格,以免破坏文件?

因此 XML 文件格式不正确并已损坏,因此出现错误:

Excel found unreadable content in file

要排除故障并修复此问题,我建议您将手动创建的 xlsx 与以编程方式创建的 xlsx 进行比较。

为此,您将两个文件扩展名从 XLSX 重命名为 ZIP > 将它们解压到不同的文件夹 > 使用 WinDiff 工具(或更好的 "OpenXML SDK Productivity Tool")比较文件。

一旦您发现它的格式错误如何更改您的代码以尝试修复它。

我使用 EPPLUS 解决了我的问题

using (ExcelPackage excelPackage = new ExcelPackage(fileStream))
{
    ExcelWorkbook excelWorkBook = excelPackage.Workbook;
    ExcelWorksheet excelWorksheet = excelWorkBook.Worksheets.First();
    excelWorksheet.Cells["C4"].Value = "123";
    excelWorksheet.Cells["D4"].Value = "321";

    excelPackage.SaveAs(memoryStream);
}