那些Excel中的脚本:读取文档信息

这一篇咱们用一个简单的例子,演示如何读取文档基本信息。每个文档都有这些基本信息,大致如下图所示。.

那些Excel中的脚本:读取文档信息

跟前几个例子不同,今天我们用ScriptLab这个工具,这是一个插件,可以在Excel,PowerPoint,Word,Outlook中使用,它所使用的代码库是标准的(用的是这个https://appsforoffice.microsoft.com/lib/1/hosted/office.js) ,与此前的Office Scripts的语法略有不同。【这其实是很不应该的】

这里用到的对象,主要有 workbook, worksheet, properties等。另外要注意,这里的代码相对更加规范一些,例如要加载某个属性,必须先加载它。

$("#run").click(() => tryCatch(run));
async function run() {  await Excel.run(async (context) => {    const wb = context.workbook;    const sheet = wb.worksheets.getActiveWorksheet();    const properties = wb.properties;    wb.load("name");    properties.load([      "name",       "author",       "lastAuthor",       "title",       "category",       "comments",       "company",       "subject"]);    await context.sync();
    const data = [      ["文件名", context.workbook.name],      ["作者", properties.author],      ["最后修改人", properties.lastAuthor],      ["标题", properties.title],      ["类别", properties.category],      ["备注", properties.comments],      ["公司", properties.company],      ["主题", properties.subject]    ];
    sheet      .getRange("A1")      .getResizedRange(data.length - 1, 1)      .values = data;
    sheet      .getUsedRange()      .getEntireColumn()      .format.autofitColumns();
    await context.sync();  });}
async function tryCatch(callback) {  try {    await callback();  } catch (error) {    console.error(error);  }}

代码运行效果如下,请参考

那些Excel中的脚本:读取文档信息

后续脚本都将使用ScriptLab来做。