基本上这个问题给出了我想要做的答案:
Google脚本创建文件夹,然后在该文件夹中创建Google Doc
但它已经5年了,我想知道现在是否有更简单的方法。在我的情况下,我有很多现有的文件夹,我想通过每隔一段时间运行的脚本在每个文件夹中创建一个特定的文件。
Thx .
编辑:
Ok,当文件夹'test folder'位于共享驱动器中时,下面的代码运行良好(在答案中使用修改过的样例脚本1)。
function testFunction() {
const notesFileName = 'test doc';
const folderName = 'test folder';
const query = "title = '" + folderName + "'";
// Find all folders that match the query.
var folders = DriveApp.searchFolders(query);
while (folders.hasNext()) {
// In all the sub-folders, of each found folder, create a file with the same name.
var folder = folders.next();
Logger.log("Found a folder: " + folder);
var subFolders = folder.getFolders();
while( subFolders.hasNext() ) {
var subFolder = subFolders.next();
Logger.log('Folder id: ' + subFolder.getId());
const doc = Drive.Files.insert({title: notesFileName, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: subFolder.getId()}]}, null, {supportsAllDrives: true});
}
}
}
我相信你的目标如下。
- 你想创建新的Google文档到特定的文件夹。
- 你有很多文件夹,你想创建新的谷歌文档。所以你想减少脚本的处理成本。
在这种情况下,我想建议使用驱动器API创建新的谷歌文档。当使用驱动API时,创建每个文件夹的谷歌文档可以与异步进程一起运行。示例脚本如下:
示例脚本1:在使用此脚本之前,请在高级谷歌服务中启用驱动器API。在这个示例脚本中,新的Google Documents在一个循环中被创建到特定的文件夹。
function sample1() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const documentIds = folderIds.map(id => Drive.Files.insert({title: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: id}]}).id);
console.log(documentIds)
}
- 在此脚本中,返回创建的文档id。
- 如果此脚本在您的实际情况下处理时间较长,请测试以下示例脚本2
示例脚本2:
在使用此脚本之前,请在高级谷歌服务中启用驱动器API。在这个示例脚本中,使用Google Apps script库使用Drive API的批处理请求将新的Google Documents创建到特定的文件夹中。通过这种方式,任务在异步进程中运行。
请安装Google Apps Script库以使用批处理请求。Ref
function sample2() {
const titleOfDocument = "sample document";
const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
const requests = {
batchPath: "batch/drive/v3",
requests: folderIds.map(id => ({
method: "POST",
endpoint: `https://www.googleapis.com/drive/v3/files`,
requestBody: {name: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [id]},
})),
accessToken: ScriptApp.getOAuthToken(),
};
const result = BatchRequest.EDo(requests); // Using GAS library
const documentIds = result.map(({id}) => id);
console.log(documentIds)
}
注意:
对于上面的样例脚本,如果您想要检索特定文件夹下的文件夹id,您还可以如下所示使用For
folderIds
。const topFolderId = "### top folder ID ###"; const folders = DriveApp.getFolderById(topFolderId).getFolders(); const folderIds = []; while (folders.hasNext()) { folderIds.push(folders.next().getId()); }
顺便说一下,在当前阶段,为了移动文件,可以使用moveTo(destination)。使用它,可以对该脚本进行如下修改:
function createDoc(folderID, name) { var folder = DriveApp.getFolderById(folderID); var doc = DocumentApp.create(name); DriveApp.getFileById(doc.getId()).moveTo(folder); return doc; }
引用:
- Files: insert of Drive API v2
- Files: create of Drive API v3
- BatchRequest