c# - 如果未安装 Excel,如何创建 Excel 实例

标签 c# excel interop comexception

在我的 C# 应用程序中,在 Excel Interop dll(作为引用)的帮助下,我正在读/写 excel 文件。如果我将此程序移动到未安装 office/excel 的系统(想想干净的机器),我会遇到以下错误。

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

上述错误是预期的,因为目标机器上没有 excel。
我的问题是,除了在目标机器上注册 Interop dll 之外,还有其他方法可以使用我的程序吗?

最佳答案

My question is, is there any other way to use my program apart from registering Interop dll on target machine?

当运行程序的计算机上未安装 Excel 时,您询问是否有任何方法可以使用使用 Excel 互操作的程序。最简洁的答案是不。如果您愿意重构您的程序以不使用互操作,则更长的答案是肯定的。

您可以使用 OOXml SDK如果您的目标 Excel 版本为 2007 及更高版本,则由 Microsoft 提供。您还可以使用第三方库,例如 Aspose如果你愿意花一点钱。

可以在 microsoft docs 中找到使用 OOXml SDK 将电子表格插入 excel 文件的示例。 .

// Given a document name, inserts a new worksheet.
public static void InsertWorksheet(string docName)
{
    // Open the document for editing.
    using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
    {
        // Add a blank WorksheetPart.
        WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
        newWorksheetPart.Worksheet = new Worksheet(new SheetData());

        Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
        string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

        // Get a unique ID for the new worksheet.
        uint sheetId = 1;
        if (sheets.Elements<Sheet>().Count() > 0)
        {
            sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
        }

        // Give the new worksheet a name.
        string sheetName = "Sheet" + sheetId;

        // Append the new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
        sheets.Append(sheet);
    }
}

关于c# - 如果未安装 Excel,如何创建 Excel 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12375943/

相关文章:

c# - 创建实体时发现重复记录错误

Excel:检查单元格是否包含文本字符串中的数字

c++ 中的 C# COM 互操作

C#读取多个Excel文件

excel - VBA 函数无返回值

c++ - 是否可以将 std::vector 传递给需要 CArray 的 MFC 函数?

c# - 是否可以使用 C# 与 Thunderbird 互操作?

c# - 在 C# 中执行参数化查询时出现 ORA-01745 错误

c# - 如何在 Windows RT 中发送击键

c# - 如何在不使用 asp.net 中的绑定(bind)和模板字段的情况下将数据表与 GridView 绑定(bind)?