【问题标题】:Word Addin: How to find a heading and insert text there?Word Addin:如何找到标题并在其中插入文本?
【发布时间】:2017-05-11 07:02:12
【问题描述】:

如何列出标题(标题 1、标题 2 等)、找到特定的(按名称)并在其中插入段落?在新的 Word JS API 中是否可行?

更新。谢谢瑞克!在此处粘贴代码可以解决问题

    await Word.run(async (context) => {
        try {
            let paragraphs = context.document.body.paragraphs;
            context.load(paragraphs, ['items']);

            // Synchronize the document state by executing the queued commands
            await context.sync();

            let listItems: HeroListItem[] = [];
            for (let i = 0; i < paragraphs.items.length; ++i) {
                let item = paragraphs.items[i];

                context.load(item, ['text', 'style', 'styleBuiltIn']);

                // Synchronize the document state by executing the queued commands
                await context.sync();

                if (item.style === 'Heading 1' || item.style === 'Heading 2') {
                    listItems.push({
                        primaryText: item.text + ' (' + item.style + ')'
                    });

                    if (item.text === 'Late days') {
                        let newLineItem = item.getNextOrNullObject();
                        context.load(item, ['text', 'style', 'styleBuiltIn']);
                        newLineItem.insertParagraph('<<<<<<<<<<<<<<My inserted text>>>>>>>>>>>>>>', 'After');
                    }
                }
            }

            this.setState({listItems: listItems});
        } catch (error) {
            this.setState({listItems: [{primaryText: 'error:' + error}]});
        }
    });

【问题讨论】:

    标签: office365 office-js word-addins


    【解决方案1】:

    我假设当您说“名称”时,您的意思是标题的文本。 这是可以做到的。您的代码应该加载所有段落。遍历它们并使用 stylestyleBuiltIn 属性来查找样式名称以“Heading”开头的那些。然后遍历那些查看 text 属性以找到您想要的。然后使用insertParagraph 方法插入新段落。

    更新:(回答下面的 OP 问题):您应该始终尽量减少对 context.sync 的调用,因此您应该尽量避免在循环中调用它。尝试使用 for 循环将每个段落添加到数组中,然后 context.load 数组并执行 context.sync。然后遍历数组并进行样式和文本检查。顺便说一句,在您添加到问题的代码中,您的第三次调用 context.load 是不必要的。你也可以删除你对context.load的第二个调用,前提是你将context.load的第一个调用重写为:

    context.load(paragraphs, ['text', 'style']);
    

    另外,您的代码不使用styleBuiltIn,因此您可以删除对它的所有引用。

    【讨论】:

    • 谢谢瑞克!题外话 - 我应该为数组中的每个元素一个接一个地执行 context.sync() 还是应该先加载所有需要的元素然后再执行一次 context.sync?
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多