如何获得Microsoft word文档文本作为字符串?



我是Microsoft Office插件和JS的新手。我正试图开发一个微软Word插件,将文件中的选定文本转换为QR码。所以我的问题是在文档中获得选定文本作为简单字符串。到目前为止,我的尝试都没有奏效。这里有一个链接,可以在文档中获取完整的文本,这有点帮助:Word插件获取完整的文档文本?我需要的是如何获得选定的文本作为一个字符串。我需要你的帮助。我尝试了以下操作:

txt = "";
await Word.run(async (context) => {
var documentBody = context.document.body;
context.load(documentBody);
return context.sync().then(function () {
console.log(documentBody.text); //full document text
console.log(document.getSelection.text); //selected only
txt = documentBody.text.getSelection();
});
});

检查脚本实验室。Word中的第一个示例正好满足了您的需求:

$("#run").click(() => tryCatch(run));
function run() {
return Word.run(function(context) {
var range = context.document.getSelection();
range.font.color = "red";
range.load("text");
return context.sync().then(function() {
console.log('The selected text was "' + range.text + '".');
});
});
}
/** Default helper for invoking an action and handling errors. */
function tryCatch(callback) {
Promise.resolve()
.then(callback)
.catch(function(error) {
// Note: In a production add-in, you'd want to notify the user through your add-in's UI.
console.error(error);
});
}

最新更新