Created
March 12, 2019 12:23
-
-
Save ndthanh/a7c4ee72a5cb7fddf72cdb8de0f35fa0 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
$("#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