Last active
August 11, 2020 21:40
-
-
Save p15martin/01443b788383255875aa1f0354ddc840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#setup").click(() => tryCatch(setup)); | |
$("#insert-range").click(() => tryCatch(insertRange)); | |
$("#delete-range").click(() => tryCatch(deleteRange)); | |
$("#clear-range").click(() => tryCatch(clearRange)); | |
async function insertRange() { | |
await Excel.run(async (context) => { | |
const sheet = context.workbook.worksheets.getItem("Sample"); | |
const range = sheet.getRange("B4:E4"); | |
range.insert(Excel.InsertShiftDirection.down); | |
await context.sync(); | |
}); | |
} | |
async function deleteRange() { | |
await Excel.run(async (context) => { | |
const sheet = context.workbook.worksheets.getItem("Sample"); | |
const range = sheet.getRange("B4:E4"); | |
range.delete(Excel.DeleteShiftDirection.up); | |
await context.sync(); | |
}); | |
} | |
async function clearRange() { | |
const trackedRange = await Excel.run(async (context) => { | |
console.log("Start...") | |
const sheet = context.workbook.worksheets.getItem("Sample"); | |
const table = sheet.tables.getItem('Table6') | |
const tableRange = table.getRange() | |
tableRange.track() | |
await context.sync() | |
console.log("Tracking table range") | |
const tableRow = await tableRange.getRow(1) | |
tableRow.track() | |
await context.sync() | |
console.log("Tracking table row") | |
tableRow.clear(Excel.ClearApplyTo.contents); | |
console.log("Cleared row") | |
await context.sync() | |
return tableRow | |
}); | |
await Excel.run(async (context) => { | |
trackedRange.untrack() | |
console.log("Untracked row") | |
return context.sync() | |
}); | |
} | |
async function setup() { | |
await Excel.run(async (context) => { | |
context.workbook.worksheets.getItemOrNullObject("Sample").delete(); | |
const sheet = context.workbook.worksheets.add("Sample"); | |
const data = [ | |
["Product", "Qty", "Unit Price", "Total Price"], | |
["Almonds", 2, 7.5, "=C3 * D3"], | |
["Coffee", 1, 34.5, "=C4 * D4"], | |
["Chocolate", 5, 9.56, "=C5 * D5"] | |
]; | |
const range = sheet.getRange("B2:E5"); | |
range.values = data; | |
range.format.autofitColumns(); | |
const header = range.getRow(0); | |
header.format.fill.color = "#4472C4"; | |
header.format.font.color = "white"; | |
sheet.activate(); | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment