【问题标题】:Office.js Add-in: Insert image/picture in Excel 2016Office.js 加载项:在 Excel 2016 中插入图像/图片
【发布时间】:2018-04-04 19:10:45
【问题描述】:

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

【问题讨论】:

  • 新的 JS API 还不支持这个特性。它在路线图中并且即将推出。需要使用 1.0 API,如下答案所示。

标签: javascript office-js office-addins


【解决方案1】:

这个答案解释了如何在 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多