为何WPF项目无法使用Microsoft.Office.Interop.Word的BuiltInDocumentProperties?
WPF中使用Microsoft.Office.Interop.Word修改内置文档属性时索引报错的解决方法
问题背景
在控制台应用中使用Microsoft.Office.Interop.Word修改Word文档内置属性(如关键词)并导出为PDF的代码可正常运行,但迁移到WPF项目后,执行document.BuiltInDocumentProperties["KeyWords"].Value = "Test Value";时触发错误:Cannot apply indexing with [] to an expression of type 'type'。
原因分析
- 控制台项目多基于.NET Framework,编译器对Interop类型的隐式转换支持更宽松,可直接通过
[]索引访问BuiltInDocumentProperties集合 - WPF项目若使用.NET Core/.NET 5+,
BuiltInDocumentProperties返回的是object类型,而非直接的Word.DocumentProperties集合,编译器无法自动识别索引器,必须显式转换类型后才能使用索引访问
解决方法
将访问内置属性的代码修改为显式转换为Word.DocumentProperties类型后再操作,修改后的代码如下:
// 显式转换类型后访问关键词属性 ((Word.DocumentProperties)document.BuiltInDocumentProperties)["KeyWords"].Value = "Test Value";
也可以通过Item属性实现相同效果:
((Word.DocumentProperties)document.BuiltInDocumentProperties).Item["KeyWords"].Value = "Test Value";
额外注意事项
操作完成后需手动释放Interop COM对象,避免Word进程残留:
document.Close(); Marshal.ReleaseComObject(document); application.Quit(); Marshal.ReleaseComObject(application);
内容的提问来源于stack exchange,提问作者Herbert Nijkamp
相关产品推荐
相关产品推荐

