2017-07-19 97 views
0

我想從我的web應用程序中刪除Excel文件的內容,但我有一些錯誤,我已經使用這個代碼:刪除Excel的內容C#

var excel = new Application(); 
var workbook = excel.Workbooks.Open(ExcelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
try 
{ 
    foreach (dynamic worksheet in workbook.Worksheets) 
    { 
     worksheet.Cells.ClearContents(); 
    } 
    workbook.Save(); 
} 
finally 
{ 
    workbook.Close(); 
    excel.Quit(); 
} 

但是當我執行我有這個錯誤應用:

Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

回答

0

你可以嘗試使用類似這樣的東西嗎?從這個question 了代碼,因此它沒有進行測試

excel.DisplayAlerts = false; 
for (int i = excel.ActiveWorkbook.Worksheets.Count; i > 0 ; i--) 
{ 
    Worksheet worksheet = (Worksheet)excel.ActiveWorkbook.Worksheets[i]; 
    worksheet.Cells.ClearContents();   
} 
excel.DisplayAlerts = true; 

但如果失敗的話,你可能最終刪除所有工作表,只是增加新的?