【问题标题】:How can i get the document title in Office 365 JavaScript API?如何在 Office 365 JavaScript API 中获取文档标题?
【发布时间】:2018-02-27 13:19:08
【问题描述】:

我正在用 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);
    });
}

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

【问题讨论】:

  • 在此期间您是否设法找到了一种明智的方法?我刚刚掉进了你用document.properties.title做的那个洞。
  • @dnmh 很遗憾没有!我卡住了!

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


【解决方案1】:

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

我对 Word API 对象模型并不十分熟悉,但这里有一些可能会有所帮助的内容。下面的代码 sn -p 获取文档的第一段(如果文档的第一行是标题,则表示文档的标题),然后用新的文本字符串更新标题的文本(同时保持任何以前的格式等)。

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));
        }
    });

注意:如果您不能假设文档的第一个段落始终是文档标题(即,如果有时文档可能没有标题,或者有时标题前面可能有一个或多个空行,例如),您需要在上面的 sn-p 中添加额外的逻辑来确定第一个 段落是否 文档的确实是一个标题,然后再继续执行替换第一段内容的逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多