Word 插件:如何找到标题并在其中插入文本?

Word Addin: How to find a heading and insert text there?

如何列出标题(标题 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}]});
        }
    });

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

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

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

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