首页 > 解决方案 > 使用 Google Apps 脚本直接在文件夹中而不是在根文件夹中创建 Google Doc 文件

问题描述

我有这个运行良好的 Google Apps 脚本:

function myFunction(e) {

  var name = e.values[1];
  var kantoor = e.values[2];

  var doc = DocumentApp.create('Sleuteloverdracht ' + name);
  var body = doc.getBody();
  body.appendParagraph('Sleuteloverdracht ' + name);
  body.appendParagraph('Uw naam is '+ name + '\n' + 'U heeft de sleutel van kantoor '+ kantoor);
  doc.saveAndClose();

}

它使用来自表单的响应的电子表格中的内容制作 Google Doc。它与触发器一起使用,当表单发送时,文档就制作好了。

但问题是 Google Doc 文件被放置在我的驱动器中,而不是与表单和电子表格相同的文件夹中。

编辑:这个Create a Google Doc file directly in a Google Drive folder主题中的问题是不一样的。我已经有一个 Doc,不想创建一个。现有的文档只需要移动到另一个文件。有关我使用的解决方案,请参阅下面的答案。

标签: google-apps-scriptgoogle-docs

解决方案


这是在特定文件夹中创建新 Google Doc 的方法。创建 Doc 时,必须设置 mime 类型。

请注意,此代码不会首先创建 Doc 文件,移动它,然后删除根驱动器中的文件。还有另一个流行的答案可以做到这一点。此代码直接在文件夹中创建一个新的 Google Doc 类型文件。

您将需要使用 Advanced Drive API。它必须在两个地方启用。

  • 从代码编辑器中选择“资源”,然后选择“高级 Google 服务”
  • 单击“Drive API”按钮,使其处于打开状态。
  • 点击链接:Google Cloud Platform API Dashboard。
  • 搜索驱动器 API
  • 从搜索列表中选择 Google Drive API
  • 启用云端硬盘 API

代码:

function myFunction(e) {
  var doc,fileResource,folder,ID_of_newFile,multipleFolders,newFile,
      newDocName,rng,sh,ss,ssFile,ssID;

  var name = e.values[1];
  var kantoor = e.values[2];

  newDocName = 'Sleuteloverdracht ' + name;//Set the name of the new file

  rng = e.range;//Get range in the spreadsheet that received the data
  sh = rng.getSheet();//Get sheet tab
  ss = sh.getParent();//Get spreadsheet
  ssID = ss.getSheetId();//Get file ID of spreadsheet - Integer

  ssFile = DriveApp.getFileById(ssID);//Get the spreadsheet file in order to get the
    //folder to put the new file in
  multipleFolders = ssFile.getParents();//Get all parent folders of the spreadsheet file

  folder = multipleFolders.next();//Get the folder of the spreadsheet

  fileResource = {
    'title': newDocName,
    "parents": [{'id':folder.getId()}],  //<--By setting this parent ID to the 
    //folder's ID, it creates this file in the correct folder
    'mimeType': 'application/vnd.google-apps.document'
  };

  newFile = Drive.Files.insert(fileResource);//Create the new document file
   // directly into the same folder as the spreadsheet
  ID_of_newFile = newFile.getId();

  //Logger.log(ID_of_newFile)

  doc = DocumentApp.openById(newFile.getId());//Open the new file as a Google document

  var body = doc.getBody();
  body.appendParagraph('Sleuteloverdracht ' + name);
  body.appendParagraph('Uw naam is '+ name + '\n' + 
    'U heeft de sleutel van kantoor '+ kantoor);
  doc.saveAndClose();

}

推荐阅读