首页 > 解决方案 > Excel.Range.Insesrt Office JS api 将单元格添加到表格

问题描述

我正在尝试使用 office js 提供的插入 API 将单元格添加到现有表中。微软官方文档提供了插入工作表的示例代码。

Excel.run(function (context) {
    var sheet = context.workbook.worksheets.getItem("Sample");
    var range = sheet.getRange("B4:E4");

    range.insert(Excel.InsertShiftDirection.down);

    return context.sync();
}).catch(errorHandlerFunction);

但我试图对表格上的表格做同样的事情。但它不起作用。

table = ctx.workbook.tables.getItem(tableName);
let range = table.getRange();
range.insert(Excel.InsertShiftDirection.down);

有没有办法做到这一点?

标签: javascriptexceloffice-jsoffice-addins

解决方案


您可以使用Excel.TableRow,示例代码:

Excel.run(function (ctx) { 
    var tables = ctx.workbook.tables;
    var values = [["Sample", "Values", "For", "New", "Row"]];
    var row = tables.getItem("Table1").rows.add(null, values);
    row.load('index');
    return ctx.sync().then(function() {
        console.log(row.index);
    });
}).catch(function(error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

该文档可在https://docs.microsoft.com/en-us/javascript/api/excel/excel.tablerowcollection?view=excel-js-preview#add-index--values-找到


推荐阅读