【问题标题】:Find the ID of the attached spreadsheet from doGet function从 doGet 函数中查找附加电子表格的 ID
【发布时间】:2016-06-13 10:01:15
【问题描述】:

如果可能的话,我希望让“openById”自动找到它所附加到的电子表格的 ID?

目前,我正在将电子表格中的单元格提取到 HTML 模板中,该模板使用单元格数据填充设计。

如果用户“复制”电子表格,则 ID(我手动输入)仍然是我正在使用的原始电子表格的 ID,而不是他们正在使用的电子表格的新电子表格 ID。

是否可以动态获取脚本附加的电子表格的 ID?

// code.gs
function doGet() {
  var template = HtmlService.createTemplateFromFile('index.html')
  template.sheet = SpreadsheetApp.openById('THE SPREADSHEET ID');

  // returning .evaluate() (an HtmlOutput object) will allow you to display this in a web app.
  // to get the string HTML content, use .getContent() on the HtmlOutput
  return template
      .evaluate();
}

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    方法openById 需要一个Id,它不返回它。可以通过在电子表格对象上调用getId 来获得一个ID。但是,doGetdoPost 函数没有活动电子表格的概念;方法SpreadsheetApp.getActiveSpreadsheet() 在从它们调用时返回null。似乎 Web 应用程序永远不会被视为绑定到电子表格,作为文档 hints at 列出触发器时。

    因此,没有直接的方法可以实现您想要的。但是有一个解决方法:指示用户执行一个函数来捕获 Id 并将其存储在 ScriptProperties 中(他们需要对此进行授权,所以onOpen 不会这样做)。示例:

    function recordId() {
      var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
      PropertiesService.getScriptProperties().setProperty('id', ssId);
    }
    
    function doGet(e) {
      var id = PropertiesService.getScriptProperties().getProperty('id');
      var ss = SpreadsheetApp.openById(id); // have access to spreadsheet
      return ContentService.createTextOutput(id);  // confirms that id is known to the script
    }
    

    您可以通过使用onOpen 创建一个将启动recordId 的菜单项来简化该过程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多