【问题标题】:Add a sheet conditionally in Excel 2016/365 with office add-ins (Javascript API)在 Excel 2016/365 中使用 Office 插件(Javascript API)有条件地添加工作表
【发布时间】:2022-01-24 08:48:41
【问题描述】:

我正在为 Excel 编写一个 Office 加载项,它需要有条件地添加工作表:当它不存在时:添加并填写它。当它在那里时:填充它。

现在我确实看到了这些API's

  • var sheet = context.workbook.worksheets.getItem("Sample");
  • var sheet = context.workbook.worksheets.add("Sample");

在这两种情况下,我最终都会得到一张名为“Sample”的工作表。但我怎么知道该选择哪个?

【问题讨论】:

    标签: javascript excel api


    【解决方案1】:

    粗略的解决方案是先尝试获取工作表,然后在失败时(.sync() 调用中的所有异步)添加工作表:

    async function checkedAddSheet() {
      Excel.run(async (context) => {
        // For debugging:
        OfficeExtension.config.extendedErrorLogging = true;
    
        var sheet = context.workbook.worksheets.getItem(NEW_DATA_SHEET_NAME);
        sheet.load("name, position");
    
        return context.sync()
          .then(function () {
            console.log(`Found worksheet named "${sheet.name}" in position ${sheet.position}`);
          });
      }).then(function () {
        console.log("Done");
      }).catch(function (error) {
        console.error(error);
        if (error instanceof OfficeExtension.Error) {
          console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
        console.log("Failed to get, let's add...");
        addSheet();
      });
    }
    
    function addSheet() {
      Excel.run(async (context) => {
        var sheet = context.workbook.worksheets.add(NEW_DATA_SHEET_NAME);
        sheet.load("name, position");
    
        return context.sync()
          .then(function () {
            console.log(`Worksheet named "${sheet.name}" was added in position ${sheet.position}`);
          });
      }).then(function () {
        console.log("Done");
      }).catch(function (error) {
        console.error(error);
        if (error instanceof OfficeExtension.Error) {
          console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
        console.log("Failed to get, let's add...");
      });
    }
    

    这可以通过检查错误的类型变得更好,但它确实有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多