更改内容控件中 table 的值

Change value of a table in content control

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

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);
        });
});

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

我想更改整个 table 的值以提供一个新数组(无需再次删除和添加整个 table)。我想保留用户制作的格式。我正在尝试这样做:

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);
        });
});

我再次设置 text 属性 的那一行没有改变任何东西,我一直在寻找一个无需删除 table 或逐个单元地执行此操作的函数。有什么想法吗?

您可以在 Word 中以与创建值类似的方式设置 table 值。

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);
    });
});