2017-07-19 96 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; 

但如果失败的话,你可能最终删除所有工作表,只是增加新的?