如何在Office 365 JavaScript API中获取文档标题?

时间:2017-09-18 22:06:30

标签: javascript office-js office-addins word-addins

我正在使用angularjs编写办公室加载项,我需要获取并设置文档标题(在文档顶部看到)。

这是我的代码:

function run() {
  Word.run(function (context) {
    var properties = context.document.properties;
    context.load(properties);
    return context.sync()
        .then(function() {
            console.log('thisDocument.properties.title', properties.title);
        })
    })
    .catch(function(error) {
        OfficeHelpers.UI.notify(error);
        OfficeHelpers.Utilities.log(error);
    });
}

但在控制台中没有打印文档标题!

1 个答案:

答案 0 :(得分:1)

您要写入控制台的 context.document.properties.title 属性是属性下显示的文件级属性标题,如果您选择文件>>信息(在Windows桌面上运行的Excel中)。它不是"标题" (文本)您在文档顶部看到的,或文件本身的名称。我怀疑如果您检查文档的文件级属性标题(通过Word UI),您会看到标题属性没有填充 - 除非您明确设置,否则不会填充。

我不太熟悉Word API对象模型,但这里可能会有所帮助。以下代码片段获取文档的第一段(如果文档的第一行是标题,将代表文档的标题),然后使用新的文本字符串更新标题的文本(同时保持任何以前的格式等。)。

Word.run(function (context) {

    // get the first paragraph 
    // (if the first line of the document is the title, this will be the contents of the first line (title))
    var firstParagraph = context.document.body.paragraphs.getFirst();
    firstParagraph.load("text");

    // get the OOXML representation of the first paragraph
    var ooXML = firstParagraph.getOoxml();

    return context.sync()
        .then(function () {
            // replace the text of the first paragraph with a new text string
            firstParagraph.insertOoxml(ooXML.value.replace(firstParagraph.text, "NEW TITLE"), "Replace");

            return context.sync();
        });

}).catch(function (error) {
        console.log("Error: " + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    });

注意 :如果您不能假设文档的第一个将始终是文档标题(即,有时文档标题)可能没有标题,或者如果有时标题前面可能有一个或多个空行,则您需要在上面的代码段中添加其他逻辑以确定是否第一个段落在继续使用替换第一段内容的逻辑之前,文档确实是一个标题。

相关问题