那些Excel中的脚本:选择图片并插入文档

这个例子展示了如何在Scriptlab中,让用户选择一个文件(本例为一个图片),然后将这个图片的内容读取到内存中,并且根据需要插入到文档的任意位置。

为了让用户能够选择文件,需要在界面上放一个选择文件的控件。这就是一个`input` 元素,并且设置为 `file` 这个类型,本例因为只允许接受图片,所以可以设置 `accept` 为对应的图片格式,可以用逗号分开多个格式。下面内容在scriptlab的 `HTML` 这个页面定义。.

<input type="file" id="uploadFile" accept=".png" /><button id="run" class="ms-Button"><span class="ms-Button-label">Run</span></button>

然后编写如下的代码。这里用到了 FileReader这个对象,然后需要将文件读取到内存,并且转换为Base64的字符串,最后通过addImage方法插入到文档中。

$("#run").click(() => tryCatch(run));
async function run() {  await Excel.run(async (context) => {    let reader = new FileReader();    let file = (document.getElementById("uploadFile") as HTMLInputElement).files[0];    const sheet = context.workbook.worksheets.getActiveWorksheet();    reader.readAsArrayBuffer(file);    reader.onload = async (e) => {      let result = convertToBase64(e.target.result as ArrayBuffer);      let picture = sheet.shapes.addImage(result);      picture.top = 100;      picture.left = 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中的脚本:选择图片并插入文档

点击Choose File按钮,弹出对话框,选择文件后,点击 Run 这个按钮,很快就能看到图片被插入到了工作表中。

那些Excel中的脚本:选择图片并插入文档