我几天前创建了this,其中我需要有关如何向所述文档添加自定义属性的帮助。
首先,我正在运行Word 1701(7766.2047)。
假设我有一个方法,我返回一个自定义属性。首先,我要检查是否已经创建了自定义属性。我会用一个简单的getItemOrNullObject(key)和..
来做到这一点据我所知,我需要返回context.sync()。然后对于实际加载数据的对象?我做了太多的返回context.sync()调用什么?
Word.run(function(context) {
var customDocProps = context.document.properties.customProperties;
context.load(customDocProps);
return context.sync()
.then(function() {
var temp = customDocProps.getItemOrNullObject("X");
return context.sync()
.then(function() {
if (!temp) {
context.document.properties.customProperties.add("X", 1234);
temp = customDocProps.getItemOrNullObject("X");
return context.sync()
.then(function() {
return temp;
});
} else {
return temp;
}
});
});
});
下面的代码抛出一个'ReferenceError:'Word'在开始时未定义',但如果我调试它就会在它中断之前运行
var customDocProps = context.document.properties.customProperties;
context.load(customDocProps);
return context.sync().{....}
还有一个问题。假设我想更新我的自定义属性,将:
Word.run(function (context) {
context.document.properties.customProperties.add("X", 56789);
return context.sync();
});
用新的值覆盖旧值?
如果你读到这里,谢谢你!任何帮助表示赞赏。 干杯!
答案 0 :(得分:3)
感谢您提出这个问题。
你的代码是正确的,除了一个小细节:所有* getItemOrNullObject方法都 NOT 返回一个JavaScript null,所以你的" if(!temp)"声明无法按预期工作。如果要验证存在,则需要调用if(temp.isNullObject)。
还有几点建议:
Word.run(function (context) {
var myProperty = context.document.properties.customProperties.getItemOrNullObject("X");
context.load(myProperty);
return context.sync()
.then(function () {
if (myProperty.isNullObject) {
//this means the Custom Property does not exist....
context.document.properties.customProperties.add("X", 1234);
console.log("Property Created");
return context.sync();
}
else
console.log("The property already exists, value:" + myProperty.value);
})
})
.catch(function (e) {
console.log(e.message);
})

我们将更新文档,因为这似乎令人困惑。
谢谢!
答案 1 :(得分:0)
我使用这些功能来获取或设置自定义属性
// sets a custom property on the current Word file
function setDocProperty (propName, propValue, callback) {
Word.run(context => {
context.document.properties.customProperties.add(propName, propValue)
return context.sync()
.then(() => {
callback(null)
})
.catch(e => {
callback(new Error(e))
})
})
}
// gets a custom property from the current Word file
function getDocProperty (propName, callback) {
Word.run(context => {
var customDocProps = context.document.properties.customProperties
// first, load custom properties object
context.load(customDocProps)
return context.sync()
.then(function () {
// now load actual property
var filenameProp = customDocProps.getItemOrNullObject(propName)
context.load(filenameProp)
return context.sync()
.then(() => {
callback(null, filenameProp.value)
})
.catch(err => {
callback(new Error(err))
})
})
.catch(err => {
callback(new Error(err))
})
})
}
您可以这样使用它们:
setDocProperty('docId', 28, () => {
console.log('property set')
})
getDocProperty('docId', (err, value) => {
if (err) {
console.log('Error getting property', err)
} else {
console.log('the property is ' + value)
}
})