script-lab icon indicating copy to clipboard operation
script-lab copied to clipboard

Suggestion: add sample how to use (any) external api from scriptlab

Open dma61 opened this issue 4 years ago • 1 comments

I want to populate an excel spreadsheet with data that should be extracted from an endpoint. I need a sample / template how to arrange this in microsoft scrip lab (office js).

dma61 avatar Oct 22 '21 08:10 dma61

Try the code wrote by me

$("#run").click(() => tryCatch(run));

async function run() {
  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    sheet.getUsedRange().clear();
    sheet.getRange("A1:D1").values = [["OrderID", "CustomerID", "EmployeeID", "OrderDate"]];
    sheet.getRange("A1:D1").format.font.bold = true;

    const data: (string | number | boolean)[][] = await fetch(
      "https://services.odata.org/V4/Northwind/Northwind.svc/Orders"
    )
      .then((x) => x.json())
      .then((x) => x.value)
      .then((x) => x.map((y) => [y.OrderID, y.CustomerID, y.EmployeeID, y.OrderDate]));

    sheet.getRange("A2").getResizedRange(data.length - 1, data[0].length - 1).values = data;
    sheet.getUsedRange().format.autofitColumns();
    sheet.getUsedRange().format.horizontalAlignment = "Left";

    await context.sync();
  });
}

/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
    console.error(error);
  }
}


chenxizhang avatar Sep 04 '22 14:09 chenxizhang

This would be a great question for Stack Overflow with the office-js tag.

wandyezj avatar Apr 04 '24 20:04 wandyezj