gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:42:34 27 4
gpt4 key购买 nike

在我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com