GetVooObject因AccessViolationException而失败

时间:2013-10-25 13:25:27

标签: .net excel c#-4.0 vsto

我正在使用Excel 2010和VSTO 4在.NET 4.0(C#)中开发Excel加载项。 在我的Excel访问器类中,我有一个属性“CurrentWorkbook”,它返回VSTO扩展活动工作簿:

public Microsoft.Office.Tools.Excel.Workbook CurrentWorkbook
{
  get
  {
    if (Globals.ThisAddIn.Application.ActiveWorkbook == null) return null;

    return Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook);
  }
}

通常,这很好用。但有些情况下,GetVstoObject失败并显示AccessViolationException

   at Microsoft.VisualStudio.Tools.Office.Runtime.Interop.IHostItemFactoryNoMAF.CreateProvider(Object document)
   at Microsoft.Office.Tools.Excel.WorkbookImpl.GetVstoObject(_Workbook workbook, IServiceProvider serviceProvider, UInt32 officeVersion)
   at Microsoft.Office.Tools.Excel.ApplicationFactoryImpl.GetVstoWorkbook(_Workbook workbook)
   at Microsoft.Office.Tools.Excel.ApplicationFactoryImpl.GetVstoObject(_Workbook workbook)
   at TNPExcelAddIn2.ConnectionLayer.ExcelAccess.ExcelAccessor.get_CurrentWorkbook()

提示: 在错误情况下,Globals.ThisAddIn.Application.ActiveWorkbook不是null,但在调试器中,您可以看到基础Sytem.__ComObject有点“损坏”,因为其m_ObjectToDataMapnull

  • 任何猜测???
  • 我该如何处理?
  • 或者我如何在使用System.__ComObject之前“测试”GetVstoObject

提前感谢您的答案, 约尔格

1 个答案:

答案 0 :(得分:2)

好的,事实证明,特定的XLSX-Workbook不行,因为XLSX-ZIP-Container中存在损坏的图形对象。 Excel本身忽略了这一点,但VSTO层似乎有问题。

我最终使用以下解决方案来捕获错误:

public Microsoft.Office.Tools.Excel.Workbook CurrentWorkbook
{
  get
  {
    return GetVSTOWorkbookByInteropWorkbook(Globals.ThisAddIn.Application.ActiveWorkbook);
  }
}

[HandleProcessCorruptedStateExceptions]
public static ExcelVSTO.Workbook GetVSTOWorkbookByInteropWorkbook(ExcelInterop.Workbook workbook)
{
    if (workbook == null) return null;

    try
    {
        return Globals.Factory.GetVstoObject(workbook);
    }
    //This also catches unhandled "AccessViolationException" in the VSTO layer because 
    //we have decorated the method by the annotation [HandleProcessCorruptedStateExceptions].
    catch (AccessViolationException ex)
    {
        //Handle exception...
    }
}

希望这对其他人也有帮助, 约尔格