2

我正在使用 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.ActiveWorkbookis not null,但在调试器中您可以看到底层Sytem.__ComObject有些“损坏”,因为它m_ObjectToDataMapnull

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

提前感谢您的回答,Jörg

4

1 回答 1

3

好的,事实证明,特定的 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...
    }
}

希望这对其他人也有帮助,Jörg

于 2013-10-29T23:20:39.597 回答