Search code examples
javascriptoffice-jsoffice-addins

Office.js Add-in: Insert image/picture in Excel (Office 365)


How do you add a simple image to a specific location on an excel spreadsheet using the new Office.js api?


Solution

  • 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();
    })