【问题标题】:Move File to a Different Folder in Google Drive将文件移动到 Google Drive 中的其他文件夹
【发布时间】:2020-08-12 21:21:08
【问题描述】:

在 Google 表格中,我有 2 列: A)“Google 云端硬盘文件 ID” B)“新文件路径”。

我喜欢可以根据单元格中的路径将文件移动到路径的脚本。如果文件夹不存在,可以创建文件夹。

我找到了这个脚本“Move File to a Different Folder in Google Drive”,但需要帮助才能让它在表格中工作

【问题讨论】:

  • 新文件路径是什么意思?例如,那会是一个文件夹 id 吗?
  • 好主意!是的,我可以改用文件夹 ID
  • 太棒了,谢谢

标签: google-apps-script google-sheets google-drive-api


【解决方案1】:

你基本上需要两个函数,但你只需要运行其中一个;这就是 ma​​in 函数。

解释:

函数 fileMover 将负责文件的移动:

function fileMover(id,targetFolderId,parentFolderId) {

  const file = DriveApp.getFileById(id)
  file.getParents().next().removeFile(file);
    try {
      DriveApp.getFolderById(targetFolderId).addFile(file);}
    
    catch(e){
      const parentFolder=DriveApp.getFolderById(parentFolderId);
      const newFolder=parentFolder.createFolder(file.getName() + " folder");
      DriveApp.getFolderById(newFolder.getId()).addFile(file);    
    }
}

ma​​in 函数将遍历列并为文件中的每一行执行 fileMover:

function main () {

  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const parentFolderId = 'parentfoldeidhere'; 
  const file_ids = sh.getRange("A2:A"+sh.getLastRow()).getValues().flat([1]);
  const folder_ids = sh.getRange("B2:B"+sh.getLastRow()).getValues().flat([1]);
  
  for (var i = 0 ; i < file_ids.length ; i++){
  fileMover(file_ids[i],folder_ids[i],parentFolderId)
  }
}

重要信息:

您可以在 ma​​in 函数中看到,有一个变量 parentFolderId。当 B 列 (Folder_ID) 没有提供正确的 ID 时,此文件夹用作所有正在创建的新文件夹的占位符。这是一种更好的做法,可以将文件组织在一个“父”文件夹中。

这是我的电子表格文件的结构。 A 列 提供了您要移动的文件的 ID 列表。 B 列 提供了您希望将文件移动到同一行中的文件夹 ID 的列表。如果B列提供了错误的文件夹ID,则会在父文件夹中创建一个新文件夹(在ma​​in函数中调整父文件夹ID)。新文件夹的名称为:nameofthefile + " folder",但这也可以在fileMover 函数的file.getName() + " folder" 中进行调整。另外,请随意调整工作表的名称,在我的例子中是 Sheet1。

【讨论】:

  • 感谢您的解决方案。执行此代码的帐户是否需要是文件和/或目标文件夹的所有者?或者他们可以简单地拥有两者的编辑权限?
猜你喜欢
  • 2013-03-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
相关资源
最近更新 更多