如何解决如何使用 JS 从 Google Drive 复制文件夹以在 Google Drive 中创建新文件夹
我想将文件夹复制到 Google Drive 中的主文件夹中。我的主要问题是当一列不为空而另一列为空时创建一个函数。 一旦创建了一个新文件夹,它必须将文件夹 URL 粘贴到其中一列中。
这是我目前所拥有的:
function addData(){
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var lr = activeSheet.getLastRow();
var lc = activeSheet.getLastColumn();
var sourceData = sourceSheet.getRange(1,1,lr,lc).getValues();
for (row in sourceData) {
if (sourceData[row][0] !== "" && sourceData[row][19] !== "") {
var rowNum = parseInt(row);
//code will go here for Folder copying and renaming and getting the new folder url
activeSheet.getRange(rowNum+1,lc).setValue("Completed"); //we will eventually change Completed with the new Folder URL
}
}
}
解决方法
主要思想是使用 Folder.getFiles()
迭代文件和使用 Folder.getFolders()
迭代文件夹。使用 Folder.createFolder(name)
创建新文件夹并使用 File.makeCopy(name,destination)
复制文件:
/**
* Copies all the files in a folder to another one.
*/
function copyFolderContents_(source,target) {
// Iterate files in source folder
const filesIterator = source.getFiles()
while (filesIterator.hasNext()) {
const file = filesIterator.next()
// Make a copy of the file keeping the same name
file.makeCopy(file.getName(),target)
}
}
/**
* Recursivelly copies a folder and all its subfolders with all the files
*/
function copyFolder_(toCopy,copyInto) {
// Makes the new folder (with the same name) into the `copyInto`
const newFolder = copyInto.createFolder(toCopy.getName())
// Copy the contents
copyFolderContents_(toCopy,newFolder)
// Iterate any subfolder
const foldersIterator = toCopy.getFolders()
while (foldersIterator.hasNext()) {
const folder = foldersIterator.next()
// Copy the folder and it's contents (recursive call)
copyFolder_(folder,newFolder)
}
}
/**
* Entry point to execute with the Google Apps Script UI
*/
function copyFolder() {
// Get the folders (by ID in this case)
const toCopy = DriveApp.getFolderById('')
const copyInto = DriveApp.getFolderById('')
// Call the function that copies the folder
copyFolder_(toCopy,copyInto)
}
您需要在 copyFolder()
上添加要复制的文件夹的 ID 和要从中复制它的文件夹的 ID。
foldersIterator
和 filesIterator
是 Google Apps 脚本迭代器。它们有一个方法 hasNext()
,如果有另一个项目,则返回它,以及一个检索它的 next()
。
请注意,copyFolder_(toCopy,copyInto)
使用自身复制其子文件夹。
参考文献
- Folder.getFiles() (Google Apps Script reference)
- Folder.getFolders() (Google Apps Script reference)
- Folder.createFolder(name) (Google Apps Script reference)
- File.makeCopy(name,destination) (Google Apps Script reference)
- Iterators (Google Ads Script concepts) (same implementation as Google Apps Script)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。