2012-09-11 41 views
14

在我的C#應用​​程序中,藉助於Excel Interop dll(作爲參考),我正在讀取/寫入excel文件。如果我將這個程序移動到沒有安裝office/excel的系統(想想幹淨的機器),我打錯了以下錯誤。如何在未安裝Excel的情況下創建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)).

由於在目標機器上沒有出色的性能,因此預計出現以上錯誤。
我的問題是,除了在目標機器上註冊Interop dll之外,還有其他方式可以使用我的程序嗎?

回答

15

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

你問,如果有任何的方式來使用你的程序,它使用的Excel互操作,當運行程序的計算機上沒有安裝Excel。最簡潔的答案是不。較長的答案是肯定的,如果你願意重構你的程序不使用互操作。

如果您要定向的Excel版本是2007及更高版本,則可以使用Microsoft提供的OOXml SDK。如果您願意花一點錢,也可以使用第三方庫,如Aspose

使用OOXml SDK將電子表格插入Excel文件的示例可在msdn找到。

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

感謝您的詳細信息。我理解向OpenXML轉變的原因,但遺憾的是,由於其他原因,我不得不再次參與互操作。爲了解決這個問題,我爲我的程序安裝了excel(作爲先決條件)。 – Mahender

0

從所有的研究,我做了,而前先登記您的COM在服務器上的Excel文件,您必須安裝Office。

12

甚至Microsoft does not recommends usein Interop libraries on a server。所以最好找到一些替代框架來爲你做Excel。爲此,我已成功使用Npoi

我知道這不是你的例外的答案。但說實話,Interop是一條無盡的麻煩和神祕的異常信息的道路。

更新2017年: - 它以建立現代您XLSX文件的OpenXML庫我還沒有使用NPOI有一段時間了,搬到我的所有項目EPPlus insted的。

+3

+1對於Npoi。我發現這是使用Excel文檔的最佳免費庫。適用於.xls和xlsx。 – burnttoast11

+2

Npoi的+1,以及「Interop是通向無盡的麻煩和神祕的異常信息的途徑。」是的,它真的很痛。 – NeverHopeless

相關問題