我正在使用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_ObjectToDataMap
为null
System.__ComObject
之前“测试”GetVstoObject
?提前感谢您的答案, 约尔格
答案 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...
}
}
希望这对其他人也有帮助, 约尔格