天天看點

Script Lab 08:單詞“卡拉OK”,Word 基礎操作準備工作運作效果代碼後記

準備工作

今天開始做一個 Word 的例子。基礎部分是相同的,差別僅僅在于 Word API 的部分。還記得第一次我們代碼的第一行從 Excel.run 開始,這裡相應要換成 Word.run 。其它部分均是相同的,包括所有的引用,差別隻在 Word 對像本身了。

本次示例的代碼是将一個段落拆分為單詞範圍,然後周遊所有範圍以格式化每個單詞,進而産生“卡拉OK”效果。以下是源碼位址(如果無法打開,請參考前期06的技巧提示部分):

https://gist.github.com/JuaneloJuanelo/92d7b4978e3487fc593a39a7a8128a30

運作效果

Script Lab 08:單詞“卡拉OK”,Word 基礎操作準備工作運作效果代碼後記

代碼

【代碼解析】

取得段落:

let paragraph = context.document.body.paragraphs.getFirst;

拆分單詞:

let words = paragraph.split([" "], true , true);

改變顔色:

words.items[i - 1].font.highlightColor = "#FFFFFF";

words.items[i].font.highlightColor = "#FFFF00";

延時效果:

await pause(200);

【全部代碼】

$("#setup").click( => tryCatch(setup));

$("#highlight").click( => tryCatch(highlightWords));

async function highlightWords 
{ 
 await Word.run(async (context) => 
 { 
 let paragraph = context.document.body.paragraphs.getFirst; 
 let words = paragraph.split([" "], true /* trimDelimiters*/, true /* trimSpaces */); 
 words.load("text"); 

 await context.sync; 
 for (let i = 0; i < words.items.length; i++) 
 { 
 if (i >= 1) 
 { 
 words.items[i - 1].font.highlightColor = "#FFFFFF"; 
 } 
 words.items[i].font.highlightColor = "#FFFF00"; 

 await context.sync; 
 await pause(200); 
 } 
 });
}

function pause(milliseconds) 
{ 
 return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function setup 
{ 
 await Word.run(async (context) => 
 { 
 context.document.body.clear; 
 context.document.body.insertParagraph( "Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.", "Start" );
 context.document.body.paragraphs .getLast .insertText( "To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching Online cover page, header, and sidebar. Click Insert and then choose the Online elements you want from the different Online galleries.", "Replace" ); 

 await context.sync; });
}

async function tryCatch(callback) 
{ 
 try 
 { 
 await callback; 
 } catch (error) 
 { 
 OfficeHelpers.UI.notify(error); 
 OfficeHelpers.Utilities.log(error); 
 }
}      

【代碼圖示】

Script Lab 08:單詞“卡拉OK”,Word 基礎操作準備工作運作效果代碼後記

後記

有一段非常重要的代碼,前面沒有提到:

words.load("text");

這裡是與 VBA/VSTO 不同的地方。我們先來看一下,如有注釋掉這句代碼會怎麼樣?

PropertyNotLoaded: 屬性“items”不可用。讀取屬性的值之前,請先對包含對象調用 load 方法,再對關聯的請求上下文調用 "context.sync"。

對于讀回 Word 資料,所有的對象都有一個特殊指令 object.load(properties) 。而其中的 “text” 正是 word 對象下的 text 屬性。其實一次可以加入多個屬性,鑒于這個部分相對複雜,以後專題介紹,目前隻需注意:避免加載不需要的屬性。

繼續閱讀