How do you add a simple image to a specific location on an excel spreadsheet using the new Office.js api?
-
1The new JS APIs don't yet support this feature. It is in the roadmap and coming soon. The 1.0 API needs to be used as shown in below answer. – Sudhi Ramamurthy Apr 04 '18 at 20:22
-
1Can I request you edit Question Title to be more generic now that you've resolved so this can be a thread for future users. IE: Just remove `2016` as this can apply to `Office 365` which many of us are using. It doesn't appear your question was specific to 2016. – FreeSoftwareServers Jan 20 '23 at 18:10
2 Answers
This answer explains how to do this in Word: https://stackoverflow.com/a/38194807/3806701, and similarly, I was able to do it this way Excel:
insertImageBase64New() {
Excel.run(async (ctx) => {
let sheet = ctx.workbook.worksheets.getItem("Sheet1");
let address = "C3";
let range = sheet.getRange(address);
range.select();
await ctx.sync();
Office.context.document.setSelectedDataAsync(this.getBase64(), {
coercionType: Office.CoercionType.Image,
imageLeft: 0,
imageTop: 0,
imageWidth: 300,
imageHeight: 100
}, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
}
});
});
}
getBase64() {
return "return "iVBORw0KGgoAAAANSUhEU..."; //put your base64 encoded image here
}
Documentation reference: https://dev.office.com/reference/add-ins/excel/rangefill
Random website I used to encode an image: https://www.browserling.com/tools/image-to-base64

- 2,782
- 27
- 39
From Excel API 1.9 you can use the method
addImage(base64ImageString: string): Excel.Shape;
from the worksheet ShapeCollections
from the documentation here https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-shapes#images you can add an image like this
Excel.run(function (context) {
var myBase64 = "your bas64string here";
var sheet = context.workbook.worksheets.getItem("MyWorksheet");
var image = sheet.shapes.addImage(myBase64);
image.name = "Image";
return context.sync();
}).catch(errorHandlerFunction);
this however inserts the shape at the top left position
after Excel 1.10 you can get the top
and left
position of a range
if you want to reposition the images you can do the foloowing
Excel.run(async (context) => {
let sheet = context.workbook.worksheets.getItem("MyWorksheet");
let cell = sheet.getRange("D5")
cell.load('top,left') //pre-load top and left
let myBase64 = "your bas64string here";
const shape = sheet.shapes.addImage(myBase64)
await context.sync()
shape.incrementLeft(cell.left) // <- left
shape.incrementTop(cell.top) // <-top
await context.sync();
})

- 112
- 2
- 4