首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Office365API中获得JavaScript文档标题?

如何在Office365API中获得JavaScript文档标题?
EN

Stack Overflow用户
提问于 2017-09-18 22:06:29
回答 1查看 900关注 0票数 3

我正在用angularjs编写一个office外接程序,我需要获得并设置文档标题(见文档顶部的文档标题)。

这是我的密码:

代码语言:javascript
复制
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);
    });
}

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

EN

回答 1

Stack Overflow用户

发布于 2017-10-12 18:14:01

要写入控制台的context.document.properties.title属性是在“属性”下显示的文件级属性标题,如果您选择“文件>>信息”(在上运行于Windows上)。您看到的不是文档顶部的“标题”(文本),也不是文件本身的名称。我怀疑,如果您检查文档的文件级属性Title (通过Word UI),您会发现标题属性没有被填充--除非您已经显式设置了它,否则不会填充它。

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

代码语言:javascript
复制
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));
        }
    });

备注:如果不能假定文档的第一段始终是文档标题(例如,有时文档可能没有标题,或者有时标题前面可能有一个或多个空行),则需要向上面的片段添加额外的逻辑,以确定文档的第一段是否确实是标题,然后再继续进行替换第一段内容的逻辑。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46288851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档