script-lab
script-lab copied to clipboard
Suggestion: add sample how to use (any) external api from scriptlab
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).
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);
}
}
This would be a great question for Stack Overflow with the office-js tag.