gpt4 book ai didi

c# - 如何使用 Excel Interop 获取 CustomDocumentProperties?

转载 作者:行者123 更新时间:2023-11-30 16:55:48 28 4
gpt4 key购买 nike

以下代码用于获取 Excel 工作簿的自定义文档属性。

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"];

前两行是对 Excel Application 的引用.一个从 VSTO 加载项内部获取引用,另一个是常规 new Application() .

使用 Application 时从 VSTO 内部来看,代码运行正常,没有任何问题。但是当使用 new Application() , workbook.CustomDocumentProperties线抛出 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)).

我试图让它在没有 VSTO 的情况下在 C# winforms 项目上工作。许多示例和教程使用 new Application()对于 Excel 互操作,但我注意到 Microsoft.Office.Interop.Excel.Application是一个接口(interface),所以使用 new在界面上对我来说实际上很奇怪。我怎样才能创建一个合适的应用程序来获取 CustomDocumentProperties

我正在使用的引用程序集:

  • Microsoft.Office.Interop.Excel v2.0.50727 版本 14.0.0.0
  • Microsoft.CSharp v4.0.30319 版本 4.0.0.0

最佳答案

I noticed that Microsoft.Office.Interop.Excel.Application is an interface, so using new on interface is actually strange to me.

这确实很奇怪,但这是设计使然。 Excel.Application 接口(interface)用 CoClass 属性修饰,告诉实际类在“实例化”接口(interface)时实例化。更多信息 here .

But when using new Application(), the workbook.CustomDocumentProperties line throws InvalidCastException:

确实又奇怪了。我自己在使用文档属性时遇到了一些问题。似乎返回的实际类与规范不同,所以我转而使用 dynamic 以防止类型转换问题。

所以不是这个:

Microsoft.Office.Core.DocumentProperties properties = workbook.CustomDocumentProperties;

使用:

dynamic properties = workbook.CustomDocumentProperties;

关于c# - 如何使用 Excel Interop 获取 CustomDocumentProperties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28981686/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com