更改内容控件

时间:2016-09-14 23:03:38

标签: javascript office365 office-addins office-js

我创建了一个Word加载项,我使用Word API 1.3在Word 2016(版本16.0.7341.2029)中插入一个表格,如下所示:



var value = [[3,4],[5,6]];

Word.run(function (ctx) {
    var table = ctx.document.body.insertTable(value.length, value[0].length, Word.InsertLocation.end, value);
    var myContentControl = table.insertContentControl();

    myContentControl.tag = 'MyTable1';
    myContentControl.title = 'This is a table';

    return ctx.sync()
        .then(function () {
            console.log('Table created');
        }).catch(function (err) {
            console.log(err);
        });
});




我在内容控件中看到具有正确值的表。 当我检查控件的text属性时,我看到一个字符串4\t5\r\n6\t7

我想更改提供新数组的整个表的值(不再删除和添加整个表)。我想保留用户的格式。我想这样做:



Word.run(function (ctx) {
    var controls = ctx.document.contentControls;
    controls.load('id, tag, title, text');

    // Get all content control, ...
    return ctx.sync()
        .then(function () {
            // ... find the one using lodash, ...
            var ctrl = _.find(controls.items, { 'tag': 'MyTable1' });
            if (ctrl) { // found
                // ... and update the value.
                ctrl.text = newValue; // <== this line does not change the text
                ctx.sync()
                    .then(function () {
                        console.log('Table should be updated');
                    }).catch(function (err) {
                        console.log(err);
                    });
            } else {
                Console.log('Unable to find table.');
            }
        }).catch(function (err) {
            console.log(err);
        });
});
&#13;
&#13;
&#13;

我再次设置text属性的行不会改变任何内容,我正在寻找一个能够在不删除表格或逐个单元格的情况下执行此操作的函数。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用与创建表格值类似的方式在Word中设置表格值。

table.values = [["a", "b"], ["c", "d"]];

以下是您的代码中的示例:

Word.run(function (ctx) {
    var ctrl = ctx.document.contentControls.getByTag("MyTable1").getFirst();
    return ctx.sync().then(function () {
        if (!ctrl.isNull) { // found
            var newValue = [['a', 'b'], ['c', 'd']];
            ctrl.tables.getFirst().values = newValue;
            ctx.sync().then(function () {
                console.log('Table should be updated');
            }).catch(function (err) {
                console.log(err);
            });
        } else {
            console.log('Unable to find table.');
        }
    }).catch(function (err) {
        console.log(err);
    });
});
相关问题