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

Mah*_*der 20 c# excel interop comexception

在我的C#应用​​程序中,在Excel Interop dll(作为参考)的帮助下,我正在读/写excel文件.如果我把这个程序移动到没有安装office/excel的系统(想想干净的机器),我就会遇到以下错误.

System.Runtime.InteropServices.COMException(0x80040154):由于以下错误,检索CLSID为{00024500-0000-0000-C000-000000000046}的组件的COM类工厂失败:80040154未注册类(HRESULT异常:0x80040154(REGDB_E_CLASSNOTREG) )).

由于目标机器没有优秀,因此预计会出现上述错误.
我的问题是,除了在目标机器上注册Interop dll之外,还有其他方法可以使用我的程序吗?

Set*_*ers 19

我的问题是,除了在目标机器上注册Interop dll之外,还有其他方法可以使用我的程序吗?

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

如果您要定位的Excel版本为2007及更高版本,则可以使用Microsoft提供的OOXml SDK.如果您愿意花一点钱,也可以使用Aspose等第三方库.

可以在Microsoft文档中找到使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)


tra*_*max 15

即使Microsoft也不建议在服务器上使用Interop库.所以最好找一些替代框架来为你做Excel.为此,我过去成功地使用了Npoi.

我知道这不是你的例外的答案.但老实说,Interop是通往无尽的麻烦和神秘异常消息的途径.

更新2017:我暂时没有使用NPOI并将我的所有项目移动到EPPlus insted - 基于OpenXML的库创建了现代xlsx文件.

  • Npoi +1.我发现它是用于处理Excel文档的最好的免费库.适用于.xls和xlsx. (3认同)
  • 为Npoi +1,"Interop是通往无尽的麻烦和神秘异常消息的途径." 是的,真的很疼. (2认同)