The below code is used to get the custom document properties for Excel workbook.
var xlApp = Globals.ThisAddIn.Application; // This works in VSTO Excel Add-in
var xlApp = new global::Microsoft.Office.Interop.Excel.Application(); // This doesn't work anywhere
xlApp.Visible = true;
global::Microsoft.Office.Interop.Excel.Workbook workbook = xlApp.Workbooks.Open(file, false, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, false, Type.Missing, Type.Missing);
global::Microsoft.Office.Core.DocumentProperties properties = workbook.CustomDocumentProperties; // Exception occurs here
global::Microsoft.Office.Core.DocumentProperty property = properties["propertyname"];
The first 2 lines are references to the Excel Application
. One obtain the reference from VSTO add-in internals, the other is a regular new Application()
.
When using the Application
from VSTO internals, the code run fines without any problems. But when using new Application()
, the workbook.CustomDocumentProperties
line throws InvalidCastException
:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Core.DocumentProperties'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2DF8D04D-5BFA-101B-BDE5-00AA0044DE52}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
I am trying to make it to work on a C# winforms project without VSTO. A lot of examples and tutorials use new Application()
for Excel interop, but I noticed that Microsoft.Office.Interop.Excel.Application
is an interface, so using new
on interface is actually strange to me. How can I create a proper Application that can get the CustomDocumentProperties
?
Reference Assemblies I am using:
- Microsoft.Office.Interop.Excel v2.0.50727 Version 14.0.0.0
- Microsoft.CSharp v4.0.30319 Version 4.0.0.0