使用 ClosedXML 保存修改后的 excel(xlsx) 文件时出错

Error while saving modified excel(xlsx) file with ClosedXML

我正在尝试使用 ClosedXML 库和以下代码在现有 excel 文件 (xlsx) 上添加标题行:

public void HandlePrintTitleRows(IList<int> sheetIndex)
{
    using (_workbook = new XLWorkbook(_filePath))
    {
        foreach (var i in sheetIndex)
        {
            IXLWorksheet workSheet = _workbook.Worksheet(i);
            workSheet.PageSetup.SetRowsToRepeatAtTop(1, 5);
        }
        _workbook.SaveAs(_filePath);
    }
}

文件路径来自 SaveFileDialog 对话框,它打开时似乎是正确的 XLWorkbook

我从 _workbook.SaveAs 方法收到此异常消息:

Attribute 'xfId' should have unique value.
Its current value '10' duplicates with others. in /x:styleSheet[1]/x:cellStyles[1]/x:cellStyle[21]
Attribute 'xfId' should have unique value.
Its current value '12' duplicates with others. in /x:styleSheet[1]/x:cellStyles[1]/x:cellStyle[24]
Attribute 'xfId' should have unique value.
Its current value '50' duplicates with others. in /x:styleSheet[1]/x:cellStyles[1]/x:cellStyle[55
Attribute 'xfId' should have unique value.
Its current value '50' duplicates with others. in /x:styleSheet[1]/x:cellStyles[1]/x:cellStyle[59]"

堆栈跟踪:

at ClosedXML.Excel.XLWorkbook.Validate(SpreadsheetDocument package) in C:\Git\ClosedXML\ClosedXML\Excel\XLWorkbook_Save.cs:line 90

at ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType, B...

我不确定如何处理这个问题,非常感谢所有提示! excel 文件之前由 Telerik.Windows.Documents.Spreadsheet.Model.Workbook class 创建,并使用 excel 应用程序正常打开。

使用 OpenXML SDK Validator 打开您的原始文件(未经 ClosedXML 修改),查看它是否是有效文件。如果原始文件中出现验证错误,请修复它们,或者您可以使用 SaveAs(_filePath, false) 重载禁用 ClosedXML 中的验证,风险自负。