那些Excel中的脚本:读取在线图片并插入文档

上一篇文章,我讲解了如何读取本地图片文件,并且将其转换为文本,插入到工作表中。但是如果我们希望读取在线图片,然后插入文档,又该如何做呢?

其实原理很类似,假设你有如下的图片,请复制好地址。.

那些Excel中的脚本:读取在线图片并插入文档

代码其实跟上一篇很类似,可能还更简单一些呢。因为这里只需要用fetch方法就可以拿到这个图片的内容,然后照样转换为base64的字符串即可。

$("#run").click(() => tryCatch(run));
async function run() {  await Excel.run(async (context) => {    const sheet = context.workbook.worksheets.getActiveWorksheet();
    const url = "https://img2.looper.com/img/gallery/things-only-adults-notice-in-kung-fu-panda/l-intro-1600295926.jpg";
    const buffer = await fetch(url).then((x) => x.arrayBuffer());    const picture = sheet.shapes.addImage(convertToBase64(buffer));    picture.top = 10;    picture.left = 10;    picture.width = 300;    picture.height = 200;
    await context.sync();  });}
/** Default helper for invoking an action and handling errors. */async function tryCatch(callback) {  try {    await callback();  } catch (error) {    // Note: In a production add-in, you'd want to notify the user through your add-in's UI.    console.error(error);  }}
function convertToBase64(input: ArrayBuffer) {  const uInt8Array = new Uint8Array(input);  const count = uInt8Array.length;  // Allocate the necessary space up front.  const charCodeArray = new Array(count) as string[];  // Convert every entry in the array to a character.  for (let i = count; i >= 0; i--) {    charCodeArray[i] = String.fromCharCode(uInt8Array[i]);  }  // Convert the characters to base64.  const base64 = btoa(charCodeArray.join(""));  return base64;}

运行起来看的效果如下

那些Excel中的脚本:读取在线图片并插入文档

看了这两篇你可能会注意到,他们都有一个共同的方法,就是将字节转换为base64字符串的,我们现在每次都需要将其定义一遍,有没有什么办法可以复用呢?

下一篇我将介绍如何导入外部模块来简化编程。