Skip to content

Instantly share code, notes, and snippets.

@ndthanh
Created March 12, 2019 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndthanh/a7c4ee72a5cb7fddf72cdb8de0f35fa0 to your computer and use it in GitHub Desktop.
Save ndthanh/a7c4ee72a5cb7fddf72cdb8de0f35fa0 to your computer and use it in GitHub Desktop.
$("#file").change(() => tryCatch(insertSheets));
async function insertSheets() {
const myFile = <HTMLInputElement>document.getElementById("file");
const reader = new FileReader();
reader.onload = (event) => {
Excel.run((context) => {
// strip off the metadata before the base64-encoded string
const startIndex = (<string>(<FileReader>event.target).result).indexOf("base64,");
const workbookContents = (<string>(<FileReader>event.target).result).substr(startIndex + 7);
const sheets = context.workbook.worksheets;
sheets.addFromBase64(
workbookContents,
null, // get all the worksheets
Excel.WorksheetPositionType.end // insert them after the current workbook's worksheets
);
return context.sync();
});
};
// read in the file as a data URL so we can parse the base64-encoded string
reader.readAsDataURL(myFile.files[0]);
}
/** 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