google-apps-script - 使用 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 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();
}
推荐阅读
- asp.net - 无法将模型从 ASP.NET MVC 中的视图传递回控制器。收到时模型为空
- r - 我的闪亮应用程序无法在闪亮的 io 服务器上正确部署
- dynamic-programming - 我如何记住我的回溯算法并使用动态编程?
- javascript - SyntaxError 不断出现
- bixby - 当话语显示为未学习时,如何在新 UI 中强制学习?
- java - 为什么找不到 springBoot {}?
- powershell - 为什么列被跳过?
- android - 我们如何使用批处理脚本将所有应用程序从 android(adb) 复制到 PC?
- javascript - 如何将内部函数值作为参数传递给其回调
- c++ - 如何在 C++ 中编写一个递归函数模板来检查作为参数提供的两个堆栈是否相同?