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

时间:2016-06-28 12:35:42

标签: javascript office-js office-app

我曾在excel中询问过How to get the formatting of a Cell using Office.js的问题。我又有了同样的问题,但这次关于ms-word,我有可能得到在word应用程序中创建的表格单元格中的格式化文本。

enter image description here

虽然我能够将所选文本作为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);
            }
        });

我只想要当前的单元格格式文本 谢谢!

1 个答案:

答案 0 :(得分:0)

优秀的问题普拉迪普。为了获得单元格格式,您需要使用当前预览的Word 1.3 API。 您可以看到如何尝试1.3 Apis here。 (注意,您需要使用该页面上公开的Office.js预览CDN!) 检查所有新的here

现在,一旦您准备尝试1.3,以下代码将为您提供单元格格式信息。一般来说,代码正在做什么

  1. 验证选择是否在表格的单元格内。
  2. 一旦验证完成,我们就会获得' body'细胞Body对象包含FONT对象,它将包含您需要的所有格式properties。(即颜色,字体名称,粗体,斜体等。您还可以使用getHtml()函数获取正文的HTML。 / LI>

    在下面找到执行此操作的代码。请注意,此代码将返回整个单元格中应用的格式。如果你想进入下一个级别,即逐字逐句获取格式信息,那么你需要在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);
                });
    
            });
        }
    
    
    

相关问题