我想通过加载项删除我的Word文档的某些内容控件,并保留其内容。我知道我可以使用this method,但是它仅支持富文本类型的内容控件,而我的则是简单文本。
所以我的方法如下:
这是我到目前为止的代码(我只想删除特定数据绑定xpath的内容控件):
Word.run(function (context) {
var xml = context.document.body.getOoxml();
return context.sync().then(function () {
var parser = new DOMParser();
var tree = parser.parseFromString(xml.value, "application/xml");
var sdts = tree.getElementsByTagName("w:sdt");
for (var i = sdts.length - 1; i >= 0; i--) {
if (sdts[i].getElementsByTagName("w:dataBinding")['0'].attributes['w:xpath'].value == "/Root[1]/MyPath[1]") {
var content = sdts[i].getElementsByTagName("w:sdtContent")['0'].childNodes[0];
sdts[i].parentNode.replaceChild(content.cloneNode(), sdts[i]);
}
}
var newXml = (new XMLSerializer()).serializeToString(tree);
newXml = '<?xml version="1.0" standalone="yes"?><? mso-application progid = "Word.Document" ?>' + newXml;
Word.run(function (context) {
var body = context.document.body;
body.clear();
return context.sync().then(function () {
Office.context.document.setSelectedDataAsync(newXml, { coercionType: Office.CoercionType.Ooxml },
function (asyncResultSetData) {
if (asyncResultSetData.status === Office.AsyncResultStatus.Succeeded) {
console.log("Success");
} else {
console.log(JSON.stringify(asyncResultSetData.error));
}
});
}).catch(function (error) {
console.log("Error: " + JSON.stringify(error));
});
}).catch(function (error) {
console.log("Error: " + JSON.stringify(error));
});
});
});
但是setSelectedDataAsync
方法返回了无效的格式错误。这是asyncResultSetData.error
的内容:
{
"name": "Invalid Format Error",
"message": "The format of the specified data object is invalid.",
"code": 2006
}
我也尝试使用此代码:
context.document.body.insertOoxml(newXml, 'Start');
但是当我执行sync()
时,出现此错误:
{
"description": "GeneralException",
"name": "RichApi.Error",
"code": "GeneralException",
"traceMessages": [],
"innerError": null,
"debugInfo": {
"code": "GeneralException",
"message": "GeneralException",
"errorLocation": "Body.insertOoxml",
"statement": "var insertOoxml=v.insertOoxml(...);",
"surroundingStatements": ["var v=context.root._getObjectByReferenceId(\"b!00000003\");", "// >>>>>", "var insertOoxml=v.insertOoxml(...);", "// <<<<<", "// Instantiate {insertOoxml}"],
"fullStatements": ["Please enable config.extendedErrorLogging to see full statements."]
},
"stack": "GeneralException: GeneralException\n at Anonymous function (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:24:282703)\n at T (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:24:216832)\n at x (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:24:216918)\n at t (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:24:216726)\n at l (https://appsforoffice.microsoft.com/lib/1/hosted/word-win32-16.01.js:24:215233)"
}
我在做什么错了?