ComException When trying to delete a worksheet from an Excel File in C#

守給你的承諾、 提交于 2019-12-13 07:15:19

问题


I'm running into an Odd problem that I cant seem to find a solution for. I'm trying to delete any work sheet in a workbook that contains a certain worksheet name and I keep getting this exception: "Unable to get the Delete property of the Worksheet class" I'm able to use the worksheet class in other places but when i try to use the Delete(); method, or even the one that sets the visibility of said sheet I get the same thing. Any help as to why would be appreciated!

Microsoft.Office.Interop.Excel.Sheets TestWorksheets = TestBook.Worksheets;
if (TestWorksheets.Count > NumberofsheetsIWantToKeep)
{
   int WorkSheetCounter = TestWorksheets.Count;
   while (WorkSheetCounter > NumberofsheetsIWantToKeep)
   {
      if(TestWorksheets[WorkSheetCounter].Name.Contains("blah"))
      {
        TestWorksheets[WorkSheetCounter].Delete();
      }
      WorkSheetCounter--;
   }
}

回答1:


turns out I had to activate the workbook and the worksheet before I could delete it. I feel silly and apologize for that!




回答2:


use below code instead of directly deleting. Activate workbook and worksheet.

   Microsoft.Office.Interop.Excel.Workbook book = TestBook;
   book.Activate();
   TestWorksheets[WorkSheetCounter].Activate();
   TestWorksheets[WorkSheetCounter].Delete();



回答3:


I had a similar issue this morning while processing an XLSX file to clean it of named references and a macro worksheet. When attempting to Delete() the sheet it would fail with error: Exception from HRESULT: 0x800A03EC. Found that even with Document Inspector in Excel could not remove the hidden worksheet. Further investigation led me to discover the sheet's visibility was set to VeryHidden. Changing the visibility to something other than VeryHidden before attempting to delete the worksheet resolved my problem.

Using the original example code from above this is what I needed to get the delete to not error.

Microsoft.Office.Interop.Excel.Sheets TestWorksheets = TestBook.Worksheets;
if (TestWorksheets.Count > NumberofsheetsIWantToKeep)
{
    int WorkSheetCounter = TestWorksheets.Count;
    while (WorkSheetCounter > NumberofsheetsIWantToKeep)
    {
        if(TestWorksheets[WorkSheetCounter].Name.Contains("blah"))
        {
            if(TestWorksheets[WorkSheetCounter].Visible == Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetVeryHidden)
            { TestWorksheets[WorkSheetCounter].Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden; }
            TestWorksheets[WorkSheetCounter].Delete();
        }
        WorkSheetCounter--;
    }
}


来源:https://stackoverflow.com/questions/39859276/comexception-when-trying-to-delete-a-worksheet-from-an-excel-file-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!