Office Word JS-通过表选择进行内容控制 [英] Office Word JS - Content Control from Table Selection

查看:100
本文介绍了Office Word JS-通过表选择进行内容控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Office JS API开发Word加载项,试图在文档中的表绑定周围添加内容控件.

I am working on a Word add-in, using the Office JS API, trying to add a Content Control around a Table Binding in the document.

我遇到的问题是使用goToByIdAsync()选择围绕表的绑定之后,仅围绕表的最后一行而不是所选内容创建了内容控件.返回ctx.document.getSelection()的值,我可以看到所选范围只是所选表中的最后一行.我需要使用Binding对象来了解Table的选定单元格范围.我在做错什么吗?

The issue I am experiencing is after the Binding around the table is selected, using goToByIdAsync(), the Content Control is created around the last row of the table only, not the selection. Returning the value of ctx.document.getSelection() I can see the selected Range is only the last row in the Selected Table. I need to use the Binding object to know the selected cell ranges of Table. Is there something I am doing wrong?

var bindingId  = '123';
var doc        = Office.context.document;

    // Create table in document.
    doc.setSelectedDataAsync(tableValue, { coercionType: Office.CoercionType.Table }, function (asyncResult) {

            // Add Binding to table
            doc.bindings.addFromSelectionAsync(Office.BindingType.Table, { id: bindingId }, function (asyncResult) {

                    // Select the table object                        
                    doc.goToByIdAsync(bindingId, Office.GoToType.Binding, { selectionMode: 'selected' }, function (asyncResult) {

                         // Create Content Control
                         createCC();
                    });

            });
    });


    function createCC(){
         Word.run(function (ctx) {
             var range = ctx.document.getSelection();
             var html  = range.getHtml();

                 return ctx.sync().then(function () {
                     console.log('Selected Range', html.value); // Only displays last row in the table.

                     var myContentControl = range.insertContentControl();
                         myContentControl.tag = bindingId;
                         myContentControl.title = 'My Content Control';

                         return ctx.sync().then(function () {
                                    //Content control for table created
                                });
                           }).catch(function (err) {
                               errorHandler(err);
                           });
                    });
    }

推荐答案

这是一个很好的问题!感谢您的询问.我建议您对如何实现所需方案进行一些更改.首先,不应将goToById用于获取任何对象的范围,这只是出于导航目的.如果您可以插入表,使用命名的内容控件包装表(为其分配标题),创建绑定(使用addFromNamedItem而不使用addFromSelection,因为您没有可靠的选择:)),它将更具确定性. ,然后只需订阅bindingSelectionChanged事件,然后对表或选定的单元格进行任何操作即可.

This is a great question! thanks for asking. I will suggest you to change a bit the approach on how to achieve the scenario you want. First of all goToById should not be used to get the range of any object, this is just for navigation purposes. It will be way more deterministic if you can insert a table, wrap it with a named content control (assigning a title to it), create a binding (using addFromNamedItem and not using addFromSelection as you don't have a solid selection :) ) , and then just subscribe to the bindingSelectionChanged event and do whatever you need to do with the table or selected cells.

以下代码显示了这一点.希望它将为您设定正确的方向.我对上面描述的每个步骤都添加了一些注释.

The following code shows just that. Hopefully it will set you up in the right direction. I added a bunch of comments of each of the steps I described above.

感谢并祝您编程愉快!

function insertTableCreateABindingAndSubscribeToEvents() {
    Word.run(function (context) { 
        //ok first we insert a table... 2 rows, 3 columns 
        var myTableData = [["Banana", "Mango", "Cherry"],["10","20","30"]];
        var myTable = context.document.body.insertTable(2, 3, "end", myTableData); //insert at the end of the body of the document.
        context.load(myTable);
        return context.sync()
            .then(function () { 
            //then we wrap the isnerted table with a content control
        var myCC = myTable.insertContentControl();
        myCC.title = "myTableTitle"; //important: assing a title so then i can use it to bind by namedItem!
        return context.sync()
        .then(function () { 
                //Now we create the binding and subscribe to the events...
                //since  we know the content control title, we can use addFromNamedItem!
    
            Office.context.document.bindings.addFromNamedItemAsync("myTableTitle", "table", {}, function (result) {
             //boom now lets subscribe to the event...
                if (result.status == "succeeded") {
                    //now lets subscribe to the selectionChanged event.\
                    result.value.addHandlerAsync(Office.EventType.BindingSelectionChanged, handler);
                }
                else { 
                    console.log("error");
                }

             } )
        })

            })

    })
        .catch(function (e) { 
            console.log(e.message);
        })


 }

function handler(args) {
//check out all the values you can get, see below how we use it to display the selected cell value...
  //  console.log("selection changed!" + args.startRow + " " + args.startColumn + " " + args.rowCount + " " + args.columnCount);
    var row;
    if (args.startRow == undefined) {
        //menas the selection is in the header!
        row = 0;
    }
    else {
         //selection not in the header...
        row = args.startRow + 1
    }

// the other thing you can try here is to get the table, and print the selected cell value..
    Word.run(function (context) {
        //this instruction selected  cell of the  table within the content control named "myTableTite"
        var mySelectedCellBody = context.document.contentControls.getByTitle("myTableTitle").getFirst().tables.getFirst().getCell(row,args.startColumn).body;
        context.load(mySelectedCellBody);
        return context.sync()
            .then(function () {
                //lets write the value of the cell (assumes single cell selected.)
                console.log(mySelectedCellBody.text);

             })
    })
        .catch(function (e) { 
            console.log("handler:" + e.message);
        })



 }

这篇关于Office Word JS-通过表选择进行内容控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆