0

In excel we create a table we have to pass a static address for adding columns to the table. I want to add columns dynamically, not bypassing the excel address. Is this possible in excel?

await Excel.run(async (context) => {
    let sheet = context.workbook.worksheets.getItem("Sample");
    let expensesTable = sheet.tables.add("A1:D1", true /*hasHeaders*/);
    expensesTable.name = "ExpensesTable";

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

    expensesTable.rows.add(null /*add rows to the end of the table*/, [
        ["1/1/2017", "The Phone Company", "Communications", "$120"],
        ["1/2/2017", "Northwind Electric Cars", "Transportation", "$142"],
        ["1/5/2017", "Best For You Organics Company", "Groceries", "$27"],
        ["1/10/2017", "Coho Vineyard", "Restaurant", "$33"],
        ["1/11/2017", "Bellows College", "Education", "$350"],
        ["1/15/2017", "Trey Research", "Other", "$135"],
        ["1/15/2017", "Best For You Organics Company", "Groceries", "$97"]
    ]);

    if (Office.context.requirements.isSetSupported("ExcelApi", "1.2")) {
        sheet.getUsedRange().format.autofitColumns();
        sheet.getUsedRange().format.autofitRows();
    }

    sheet.activate();

    await context.sync();
});
Shiv Yadav
  • 467
  • 2
  • 11

1 Answers1

1

The following sample code shows how to create a table add rows to it in a more dynamic way compared the code sample that you provided in your question.

  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();

    const header = ["Date", "Merchant", "Category", "Amount"];

    const rows = [
      ["1/1/2017", "The Phone Company", "Communications", "$120"],
      ["1/2/2017", "Northwind Electric Cars", "Transportation", "$142"],
      ["1/5/2017", "Best For You Organics Company", "Groceries", "$27"],
      ["1/10/2017", "Coho Vineyard", "Restaurant", "$33"],
      ["1/11/2017", "Bellows College", "Education", "$350"],
      ["1/15/2017", "Trey Research", "Other", "$135"],
      ["1/15/2017", "Best For You Organics Company", "Groceries", "$97"]
    ]

    // Add header to the grid
    const headerRange = sheet.getRange("A1").getResizedRange(0, header.length - 1);
    headerRange.values = [header];

    // Add table
    const expensesTable = sheet.tables.add(headerRange, true /*hasHeaders*/);
    expensesTable.name = "ExpensesTable";

    // Add rows to the table
    expensesTable.rows.add(null /*add at the end*/, rows);

    // Autofit columns and rows
    sheet.getUsedRange().format.autofitColumns();
    sheet.getUsedRange().format.autofitRows();

    await context.sync();
  });