如何使用应用程序脚本 google 驱动器从 google sheet 中的父文件夹中获取所有子文件夹名称的列表

How to get list all sub folders name from parent folders in google sheet with apps script google drive

如何将 google 驱动器中的所有子文件夹名称列出到 google sheet 中?

这是代码,它可以工作,但我无法将它们放入 google sheets.

enter image description here 在记录器的地方,我需要替换 google sheet。在这种情况下请帮帮我?

如果您打算使用 custom function to write the list of sub-folder names in Google Sheets, It will not work because your function require authorization when using DriveApp it will throw an error message You do not have permission to call X service., the service requires user authorization and thus cannot be used in a custom function as stated here

您可以使用 Spreadsheet Service 在 Google 表格中写下您的子文件夹名称。但是你需要指定具体的sheet和你要写入数据的单元格。

示例代码:

function findSubFolder(){
  var childFolder = DriveApp.getFolderById('xxxxxxxx').getFolders();
  var activeSheet = SpreadsheetApp.getActiveSheet();
  var activeCell = activeSheet.getActiveCell();

  var childNames = [];
  while (childFolder.hasNext()) {
    var child = childFolder.next();
    Logger.log(child.getName());
    childNames.push([child.getName()]);
  }
  
 
 activeSheet.getRange(activeCell.getRow(),activeCell.getColumn(),childNames.length,1).setValues(childNames);
}

它有什么作用?

  1. 使用 SpreadsheetApp.getActiveSheet() and the active cell using Sheet.getActiveCell()
  2. 获得活跃 sheet
  3. 获取所有子文件夹名称并使用 Array.prototype.push()
  4. 将其添加到 childNames 数组

Notice that when I pushed the child names I used [sub-folder name], This is needed when we want use Range.setValues() which accepts a 2-d array where I want to have multiple rows.

  1. 从活动单元格开始将 childNames 数组写入活动 sheet。使用 Sheet.getRange(row, column, numRows, numColumns) and Range.setValues(values)

输出:


如果你想在单个单元格(在你的活动单元格中)写子文件夹名称,你可以替换

activeSheet.getRange(activeCell.getRow(),activeCell.getColumn(),childNames.length,1).setValues(childNames);

activeCell.setValue(childNames.flat().toString());

输出: