如何使用 Apps 脚本生成带有嵌入式 AppScript 的 Google 文档?

How to generate a Google Docs with an embedded AppScript, using Apps Script?

我有兴趣使用我的库中的特定 Apps 脚本生成 Google 文档。 我创建文档的方式基本上是通过 Jeff Everhart 的代码 here.

是否可以更改代码以使新的 Google 文档从一开始就具有嵌入式 Apps 脚本?

我的缩减代码:

  function createNewGoogleDocs() {
      const googleDocTemplate = DriveApp.getFileById('The template ID goes here');
      const destinationFolder = DriveApp.getFolderById('The destination folder ID goes here');

      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
      const rows = sheet.getDataRange().getValues();
  
  
    rows.forEach(function(row, index) {
      if (index === 0 ) return;
      if(row[rows[0].length - 1]) return;


      const copy = googleDocTemplate.makeCopy(`First Column Name (${row[0]})`, destinationFolder);
      const doc = DocumentApp.openById(copy.getId());
    
      // Hopefully here we can have the addition of the the Apps Script on the new Docs

      doc.saveAndClose();
      const url = doc.getUrl();
      sheet.getRange(index+1, rows[0].length).setValue(url);


    })

  }

如果您的目标是创建绑定到文档的 Apps 脚本项目,则必须从该特定文档创建它。正如docs上所说:

A script is bound to a Google Sheets, Docs, Slides, or Forms file if it was created from that document rather than as a standalone script. The file that a bound script is attached to is called a "container." Bound scripts generally behave like standalone scripts except that they do not appear in Google Drive, they cannot be detached from the file they are bound to, and they gain a few special privileges over the parent file.

如果您的最终目标是使用来自不同 Apps 脚本项目的嵌入式 Apps 脚本创建文档,您必须先创建该 Doc/script 作为模板,然后使用 makeCopy创建 Doc/script.

的副本

我记录这个答案是为了帮助这个社区的其他人,如果您需要进一步的帮助,请随时发表评论。