Office.js加载项:在Excel 2016中插入图像/图片

时间:2018-04-04 19:10:45

标签: javascript office-js office-addins

如何使用新的Office.js api将简单图像添加到Excel电子表格中的特定位置?

2 个答案:

答案 0 :(得分:2)

这个答案解释了如何在Word中执行此操作:https://stackoverflow.com/a/38194807/3806701,同样,我能够以这种方式执行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
}

文档参考:https://dev.office.com/reference/add-ins/excel/rangefill

随机网站我用来编码图像:https://www.browserling.com/tools/image-to-base64

答案 1 :(得分:1)

在Excel API 1.9中,您可以使用方法

addImage(base64ImageString: string): Excel.Shape;

从工作表ShapeCollections

https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-shapes#images此处的文档中,您可以添加这样的图像


    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);

这会在左上角插入形状

在Excel 1.10之后,您可以获取范围的topleft位置

如果要重新定位图像,可以进行对齐

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