写入Workbook.CustomDocumentProperties时,“价值不在预期范围内”

从C#编写的控制台应用程序中进行如下所示的简单分配:

workbook.CustomDocumentProperties.Item["PropertyName"] = "Property Value"; 

产生以下错误:

 {"Value does not fall within the expected range."} Data: {System.Collections.ListDictionaryInternal} HResult: -2147024809 HelpLink: null IPForWatsonBuckets: 0x633f1015 InnerException: null IsTransient: false Message: "Value does not fall within the expected range." ParamName: null RemoteStackTrace: null Source: "System.Dynamic" StackTrace: " at System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message)\r\n at CallSite.Target(Closure , CallSite , Object , String , Object )\r\n at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)\r\n at CustomDocumentProperties.Program.WriteToExcelCustomDocumentProperties(String excelFile, String outputFolder, String propertyName, Object propertyValue) in C:\\Sathyaish\\DotNet\\CustomDocumentProperties\\CustomDocumentProperties\\Program.cs:line 100" TargetSite: {Void CheckThrowException(Int32, System.Dynamic.ExcepInfo ByRef, UInt32, System.String)} WatsonBuckets: null _HResult: -2147024809 _className: null _data: {System.Collections.ListDictionaryInternal} _dynamicMethods: {object[2]} _exceptionMethod: {Void CheckThrowException(Int32, System.Dynamic.ExcepInfo ByRef, UInt32, System.String)} _exceptionMethodString: null _helpURL: null _innerException: null _ipForWatsonBuckets: 0x633f1015 _message: "Value does not fall within the expected range." _remoteStackIndex: 0 _remoteStackTraceString: null _safeSerializationManager: {System.Runtime.Serialization.SafeSerializationManager} _source: "System.Dynamic" _stackTrace: {sbyte[96]} _stackTraceString: null _watsonBuckets: null _xcode: -532462766 _xptrs: 0x00000000 m_paramName: null 

我第一次尝试调用CustomDocumentProperties属性的Add方法,如下所示:

 workbook.CustomDocumentProperties.Add("PropertyName", "Property Value"); 

当失败的时候,我回顾了这个文件 , 这个文件如下(重点是我的):

该属性返回整个自定义文档属性的集合。 使用Microsoft.Office.Core.DocumentProperties.Item(System.Object)属性返回集合的单个成员(Microsoft.Office.Core.DocumentProperties对象),方法是指定属性的名称或集合索引(如一个号码)。

在Word中(大概在Excel中),如果该属性不存在,则可以使用CustomDocumentProperties.Add方法对其进行设置。 但是,您需要确保传递一个Type参数,在您的情况下这将是MsoDocProperties.msoPropertyTypeString。

希望这可以帮助。