2017-09-13 11 views
0

我試圖通過Office.js更新一個新的Word文檔中的一組段落。下面的代碼是一個按預期順序循環的異步鏈。搜索段落的第一個調用返回rangeCollection正確,但所有後續調用返回一個空seachResults.items對象。如何在Office.js中對新Word文檔執行多個段落搜索(包含更新)?

不幸的是,我沒有能力做一個完整的文檔搜索的奢侈。我已經有一個段落索引列表,我需要找到與這些段落中的已知文本,以突出顯示

任何想法?

var processDocAsync = function (context, paragraphs, onComplete) { 

    // A recursive helper function to work on the n'th paragraph 
    function getAndProcessParagraph(index) { 

     // stop processing 
     if (index == paragraphs.items.length) { 
      onComplete(); 
     } else { 
      // Main recursive case 

      // search the indexth paragraph 
      var options = Word.SearchOptions.newObject(context); 
      options.matchCase = false 

      var searchResults = paragraphs.items[index].search('the', options); 
      context.load(searchResults, 'text, font'); 

      context.sync().then(function() { 

       // Highlight all the "THE" words in this paragraph 
       try { 

        // Queue a command to change the font for each found item. 
        if (searchResults.items) { 
         for (var j = 0; j < searchResults.items.length; j++) { 
          searchResults.items[j].font.color = '#FF0000' 
          searchResults.items[j].font.highlightColor = '#FFFF00'; 
          searchResults.items[j].font.bold = true; 
         } 
        } 
       } catch (myError) { 
        console.log(myError.message); 
       } 

       // Synchronize the document state by executing the queued-up commands, 
       // then move on to the next paragraph 
       return context.sync().then(getAndProcessParagraph(index + 1)); 
      }); 
     } 
    } 

    // Begin the recursive process with the first slice. 
    getAndProcessParagraph(0); 
} 

var openProcessedDoc = function (base64str, documentId) { 

    Word.run(function (context) { 

     var myNewDoc = context.application.createDocument(base64str); 
     context.load(myNewDoc); 

     var paragraphs = context.document.body.paragraphs; 
     paragraphs.load(paragraphs, 'text, font'); 

     return context.sync().then(function() { 
      processDocAsync(context, paragraphs, processCompleted) 
     }); 
    }); 
}; 

var processCompleted = function() { 
    console.log('Process completed'); 
} 

回答

0

優秀的問題。這是一個典型的如何使用承諾和異步模式遍歷集合中的集合的例子。

Please setup script lab(您可以使用一個很酷的插件來嘗試代碼片段)。跳轉至7:46 on this video以查看如何加載yaml。

load this yaml在腳本實驗室中,並查看如何執行此操作的示例。該示例並不完全符合您的需求(它基本上遍歷段落中的單詞集合),但希望您可以針對您的特定場景模仿此模式。

快樂編碼!

相關問題