在Google表格脚本中对listFilesByName的结果进行排序

时间:2016-04-29 14:04:17

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

我正在Google表格中制作一个标签,以跟踪特定文件夹中的文件。我已成功修改了我在网上找到的脚本以按文件夹ID获取列表,但我似乎无法弄清楚如何按名称顺序显示结果。以下是我使用的代码,但我将文件夹ID替换为myFolderId:

 /**
 * List all files in Google Drive folder.
 *
 * @param {string} folderName    (optional) Name of folder on Google Drive
 *
 * Adapted from:
 * http://ctrlq.org/code/19854-list-files-in-google-drive-folder
 * https://gist.github.com/hubgit/3755293
 */
function listFilesInFolder(id) {
  // If we have not been provided a folderName, assume we will interact with     user.
  var interactive = (typeof folderName === 'undefined');

  // Get name of folder to list
  if (interactive) {
    id = 'myFolderId';
  }

  if (id === '')
    return;  // No name provided, exit quietly

  var folder = DriveApp.getFolderById(id);
  var contents = folder.getFiles();

  var file, data, sheet = SpreadsheetApp.getActiveSheet();
  sheet.clear();

  sheet.appendRow(["Name", "Date"]);

  // Loop over files in folder, using file iterator
  while (contents.hasNext()) {
    file = contents.next();

    if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
      // Skip displaying spreadsheets - I don't know why...
      continue;
    }

    data = [ 
      file.getName(),
      file.getDateCreated(),
    ];

    sheet.appendRow(data);
  }
}

2 个答案:

答案 0 :(得分:3)

第一个选项,对工作表进行排序

enter image description here

第二个选项,我试图评论脚本,以便您了解步骤

/*
 * Logs in a SpreadSheet the files of a given folder
  * @param {string} folder id
 */

function listFilesInFolder(id){
  // You can change it and get ss from a given ID
  var sheet = SpreadsheetApp.getActiveSheet();

  // array to hold our data
  var data = [];

  // An iterator that allows scripts to iterate over a potentially large collection of files
  var files = DriveApp.getFolderById(id).getFiles();

  // We loop on iterator and append results to an array
  while (files.hasNext()) {
   var file = files.next();
   // we append our data with result, we have now an array of files
   data.push(file);
  }

  // lets sort our array
  data = data.sort(function(file1, file2){
      if (file1.getName().toLowerCase() < file2.getName().toLowerCase())
          return -1;
      else if (file1.getName().toLowerCase() > file2.getName().toLowerCase())
          return 1;
      else 
        return 0;
    }
  )

  // lets add it to our sheet
  // some labels
  sheet.appendRow(["Name", "Date"]);
  // real data
  data.forEach(function(file){
    sheet.appendRow([file.getName(), file.getDateCreated()])
  })
}

gist link

答案 1 :(得分:0)

在此行末添加

sudo