2017-05-11 33 views
0

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

回答

0

我認爲當你說「名字」你的意思是標題的文本。 這可以做到。你的代碼應該加載所有的段落。遍歷它們並使用風格styleBuiltIn屬性來查找樣式名稱以「標題」開頭的樣式。然後遍歷那些查看文本屬性的人以找到您想要的人。然後使用insertParagraph方法插入新段落。

更新:(響應OP的問題):你應該總是最小化呼叫context.sync,所以你應該儘量避免在循環中調用它。嘗試使用for循環將每個段落添加到數組,然後context.load該數組並執行context.sync。然後遍歷數組並進行風格和文本檢查。順便說一句,在你添加到你的問題的代碼中,你的第三個電話context.load是不必要的。您也可以刪除你的context.load秒呼叫,前提是你改寫context.load第一個電話爲:

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

而且,您的代碼不使用styleBuiltIn,這樣你就可以刪除所有引用。

+0

謝謝瑞克!題外話題 - 我應該爲數組中的每個元素逐個執行context.sync(),還是應該先加載所有需要的元素,然後再執行一次context.sync? – ZakiMa

相關問題