【问题标题】:Automatically Creating Google Drive Hyperlinks of Files Within Subfolders自动创建子文件夹中文件的 Google Drive 超链接
【发布时间】:2021-05-04 12:56:03
【问题描述】:

所以我有下面的脚本,它允许我在同一目录中自动创建文件的谷歌驱动器超链接:

function myFunction() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getActiveSheet();
  var c=s.getActiveCell();
  var fldr=DriveApp.getFolderById(*[insert id]*);
  var files=fldr.getFiles();
  var names=[],f,str;
  while (files.hasNext()) {
    f=files.next();
    str='=hyperlink("' + f.getUrl() + '")';
    str2 = f.getName();
    names.push([str2,str]);
  }

  s.getRange(c.getRow(),c.getColumn(),names.length,2).setValues(names);
       
}

不过,我是个新手,所以我真的不知道如何让它搜索每个子文件夹以及获取它们的超链接。我觉得好像这可能相对简单,但我对谷歌脚本的了解不够,无法做到这一点(如果是 python,我可以轻松做到这一点)。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript google-apps-script hyperlink google-drive-api


    【解决方案1】:

    我相信你的目标如下。

    • 您要检索特定文件夹下的所有文件,并将 URL 和文件名的值放到电子表格中。
    • 特定文件夹有子文件夹。
    • 您希望使用 Google Apps 脚本实现此目的。

    修改点:

    • 在您的脚本中,文件是从特定文件夹下检索的。
    • 为了检索特定文件夹下的所有文件,包括子文件夹,需要遍历所有子文件夹。

    当以上几点反映到您的脚本中时,它变成如下。在本次修改中,使用了Drive service

    修改脚本:

    function myFunction() {
      // Method for retrieving the file list from the specific folder including the subfolders.
      const getAllFiles = (id, list = []) => {
        const fols = DriveApp.getFolderById(id).getFolders();
        let temp = [];
        while (fols.hasNext()) {
          const fol = fols.next();
          temp.push(fol.getId());
          const files = fol.getFiles();
          while (files.hasNext()) {
            const file = files.next();
            list.push([`=hyperlink("${file.getUrl()}")`, file.getName()]);
          }
        }
        temp.forEach(id => getAllFiles(id, list));
        return list;
      }
    
      const folderId = "###"; // Please set the folder ID.
      const names = getAllFiles(folderId);
    
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var s = ss.getActiveSheet();
      var c = s.getActiveCell();
      s.getRange(c.getRow(), c.getColumn(), names.length, 2).setValues(names);
    }
    

    参考资料:

    【讨论】:

    • 啊,有道理。非常感谢您的澄清和帮助。
    • @KLonge 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多