簡體   English   中英

如何使用office.js格式化Word中表格的當前單元格

[英]How do I get the formatting the Current cell of the table in Word using office.js

我問了一個有關如何在Excel中使用Office.js獲取單元格格式的問題。 我再次有同樣的問題,但是這次關於ms-word的問題是,我可能會得到在word應用程序中創建的表格單元格中存在的格式化文本。

在此處輸入圖片說明

雖然我可以將選定的文本作為html來獲取,但是這給了我所需的樣式

 Office.context.document.getSelectedDataAsync(Office.CoercionType.Html,
        function (result) {
            if (result.status === Office.AsyncResultStatus.Succeeded) {
                showNotification('The selected text is:', '"' + result.value + '"');
            } else {
                showNotification('Error:', result.error.message);
            }
        });

我只想要當前單元格格式的文本,謝謝!

很好的問題Pradeep。 為了獲得單元格格式,您需要使用當前預覽的Word 1.3 API。 您可以在此處查看如何嘗試1.3 Apis。 (請注意,您需要使用該頁面上公開的Office.js CDN預覽版!) 在此處檢查所有新功能。

現在,一旦您准備嘗試1.3,下面的代碼將為您提供單元格格式信息。 一般來說,代碼在做什么

  1. 驗證所選內容是否在表的單元格內。
  2. 驗證完成后,我們將獲得單元的“主體”。 主體對象包含FONT對象,該對象將包含您需要的所有格式屬性 (即顏色,字體名稱,粗體,斜體等)。您還可以使用getHtml()函數獲取主體的HTML。

在下面的代碼中執行此操作。 請注意,此代碼將返回您在整個單元格中應用的格式。 如果要轉到下一層,即逐字獲取格式信息,則需要在body對象上應用split方法,這樣就可以遍歷並獲取每個返回范圍的格式信息。 希望這會有所幫助! 編碼愉快!!

 function getFormattedText() { Word.run(function (context) { //step 1: lets get the selection's range. and find out if its within a table cell..... var mySelection = context.document.getSelection().parentTableCell; context.load(mySelection); return context.sync() .then(function () { if (mySelection.isNull == true) { //selection is not within a cell..... console.log("selection not in a header"); } else { // the selection is inside a cell! lets get the content.... var body = mySelection.body; context.load(body, { expand: 'font' }); return context.sync() .then(function () { console.log(body.font.name + " " + body.font.color); // at this point all the font properties are available, bold, italic color.. etc... }) .catch(function (e) { console.log(e.message); }); } }) .catch(function (e) { console.log(e.message); }); }); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM