如果未安装Excel,如何创buildExcel的实例

在我的C#应用​​程序,在Excel Interop DLL(作为参考)的帮助下,我正在阅读/写入Excel文件。 如果我把这个程序移动到没有安装office / excel的系统(想想干净的机器),我打错了。

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

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

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

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

您可以使用由Microsoft提供的OOXml SDK ,如果您定位的Excel版本是2007年以上。 如果你愿意花一点钱,也可以使用Aspose等第三方库。

使用OOXml SDK将电子表格插入Excel文件的示例可以在msdn上find。

// 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); } } 

即使Microsoft不推荐在服务器上使用Interop库 。 所以最好find一些替代框架来为你做Excel。 为此我已经成功地使用了Npoi 。

我知道这不是你的例外的答案。 但说实话,Interop是一个无尽的麻烦和神秘的exception信息的path。

2017年更新 :我现在还没有使用过NPOI,并将所有的项目都移到了EPPlus insted – 基于OpenXML的库中,这个库创build了现代的xlsx文件。

你可以用RegSrv32注册你的COM

链接: http : //msdn.microsoft.com/en-us/library/ms859484.aspx

使用前您必须注册您的COM

从前一段时间我需要与服务器上的Excel文件进​​行交互的研究中,您必须安装Office。