如何通过“添加”一次将多行添加到Excel中?

时间:2017-12-28 20:43:54

标签: javascript office-js excel-addins

我试图在标题下添加多行数据。这将是一个新表。所有这些都在同一个事件处理程序上运行。

目前,表确实已创建,而标头和标头值也是如此。但是,不会加载数据行。

这是我创建表格并填充标题和行的代码:

function createTable() {
  Excel.run(function (context) {

    const currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
    const expensesTable = currentWorksheet.tables.add("A1:D1", true /*hasHeaders*/);
    expensesTable.name = "ExpensesTable";

    expensesTable.getHeaderRowRange().values = 
       [["Date", "Merchant", "Category", "Amount"]];

    expensesTable.rows.add(null /*add at the end*/, [
       ["1/1/2017", "The Phone Company", "Communications", "120"],
       ["1/2/2017", "Northwind Electric Cars", "Transportation", "142.33"],
       ["1/5/2017", "Best For You Organics Company", "Groceries", "27.9"],
       ["1/10/2017", "Coho Vineyard", "Restaurant", "33"],
       ["1/11/2017", "Bellows College", "Education", "350.1"],
       ["1/15/2017", "Trey Research", "Other", "135"],
       ["1/15/2017", "Best For You Organics Company", "Groceries", "97.88"]
    ]);

    expensesTable.columns.getItemAt(3).getRange().numberFormat = [['€#,##0.00']];
    expensesTable.getRange().format.autofitColumns();
    expensesTable.getRange().format.autofitRows();

    return context.sync();
  })
  .catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

这将产生此错误:

Error: InvalidArgument: The argument is invalid or missing or has an incorrect format.

Debug info: {
  "code":"InvalidArgument",
  "message":"The argument is invalid or missing or has an incorrect format.",
  "errorLocation":"TableRowCollection.add"
}

我一直在阅读有关tableRowCollection对象及其添加方法的the JS API docs,但我不知道我在这里做错了什么。任何帮助都将是美妙的!

1 个答案:

答案 0 :(得分:2)

感谢上面的评论,我意识到我无法访问1.1版以上的API版本。这是因为有一个旧版本的Excel。我更新了Excel,现在正在运行16.0的当前版本,构建8730.2046。

enter image description here

请参阅this page for details了解哪些API版本适用于哪些Excel版本。