如何使用新的Office.js api将简单图像添加到Excel电子表格中的特定位置?
答案 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之后,您可以获取范围的top
和left
位置
如果要重新定位图像,可以进行对齐
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();
})