我正在寫一個適用於excel文件的應用程序。 我需要一個功能來刪除工作表。 我必須使用程序集Microsoft.Office.Interop.Excel.dll。如何在未安裝MS Office的計算機上使用Microsoft.Office.Interop.Excel?
它的運行開發機器上很好,但是當我嘗試將其部署到服務器,我得到一個錯誤:
Could not load file or assembly 'office, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies
我明白這個問題時,一臺機器上沒有安裝MS Office的發生。 客戶不想以任何代價在服務器上安裝和購買MS Office。
我在開發者機器上安裝了「Redistributable Primary Interop Assemblies」,如下所示:http://forums.asp.net/t/1530230.aspx/1 並重新編譯我的項目。
代碼示例:
public bool DeleteSheet(string tableName)
{
Excel.Application app = null;
Excel.Workbooks wbks = null;
Excel._Workbook _wbk = null;
Excel.Sheets shs = null;
bool found = false;
try
{
app = new Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
wbks = app.Workbooks;
_wbk = wbks.Add(xlsfile);
shs = _wbk.Sheets;
int nSheets = shs.Count;
for (int i = 1; i <= nSheets; i++)
{
Excel._Worksheet _iSheet = (Excel._Worksheet)shs.get_Item(i);
if (_iSheet.Name == tableName)
{
_iSheet.Delete();
found = true;
Marshal.ReleaseComObject(_iSheet);
break;
}
Marshal.ReleaseComObject(_iSheet);
}
if (!found)
throw new Exception(string.Format("Table \"{0}\" was't found", tableName));
_wbk.SaveAs(connect, _wbk.FileFormat, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
finally
{
_wbk.Close(null, null, null);
wbks.Close();
app.Quit();
Marshal.ReleaseComObject(shs);
Marshal.ReleaseComObject(_wbk);
Marshal.ReleaseComObject(wbks);
Marshal.ReleaseComObject(app);
}
return true;
}
例外
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)).
發生就行
app = new Excel.Application();
任何人都可以就如何得到這個功能成功合作建議?
文檔是 - 互操作程序集只是告訴.NET如何調用Excel的COM庫。他們沒有任何功能。另一個流行的閱讀/寫作.xlsx文件:http://closedxml.codeplex.com/ – Govert 2012-07-12 09:12:55
謝謝。 我會嘗試這些庫。 – 2012-07-12 09:40:36
碰巧,您甚至無法在未安裝Office的情況下_BUILD_包含對Microsoft.Office.Core **的引用的項目。其他文檔級別的Interop程序集引用似乎可以編譯但不能運行。我的解決方法是刪除明確的** Microsoft.Office.Core **引用,並用**動態**和** var **關鍵字替換它們,這些關鍵字允許在intellisense完成其開發人員機。 – CZahrobsky 2014-08-08 17:09:41