排序listFilesByName结果在谷歌表脚本

问题描述 投票:1回答:2

我在谷歌工作表制作标签来跟踪文件的特定文件夹中。我已经成功地修改了剧本,我发现在网上得到按文件夹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);
  }
}
google-apps-script google-sheets google-drive-sdk
2个回答
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


0
投票

在末尾加上这一行

//for sorting the Name column    
sheet.sort(1); 
© www.soinside.com 2019 - 2024. All rights reserved.