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

时间:2017-09-11 08:48:59

标签: c# excel ms-office office-interop com-interop

一个简单的赋值,如下面用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

我首先尝试在Add属性上调用CustomDocumentProperties方法,如下所示:

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

当失败时,我回顾了the documentation,其评论如下(强调我的):

  

此属性返回自定义文档的整个集合   属性。 使用   Microsoft.Office.Core.DocumentProperties.Item(System.Object)属性   返回集合中的单个成员(a   Microsoft.Office.Core.DocumentProperties对象)通过指定   属性的名称或集合索引(作为数字)。

1 个答案:

答案 0 :(得分:1)

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

希望这有帮助。