On my Google Drive I have a folder containing 2006 files. These files are sorted by names. (from A -> Z) Here's the exact order of the files inside my folder: https://gist.github.com/cuzureau/a36deb8e02ab0f2e0523cd58f2cf0950
Now, I also have a Google Sheet with the same file names written in a column. One file name per cell. They are order alphabetically (from A -> Z) Here's the exact order of the files inside the column: https://gist.github.com/cuzureau/6fe722b821ce3aa60b697819b64d6b05
The files names are not sorted in the same order. How can I do that ?
Maybe I should use a formula in Google Sheets to reorder the files names in the column ?
These are two possible solutions using Google Apps Script (both tested with the first 100 files):
Extensions > Apps Script
const sheet = SpreadsheetApp.getActiveSheet()
function myFunction() {
const folderId = "<FOLDER_ID>"
// Get all files in the folder
const files = DriveApp.getFolderById(folderId).getFiles()
const toShortFiles = []
while (files.hasNext()) {
// save all the names
const file = files.next()
toShortFiles.push(file.getName())
}
// short A-Z
const shorted = toShortFiles.sort((a, b) => a.localeCompare(b)).map(n => [n])
sheet.getRange(1, 1, shorted.length, 1).setValues(shorted)
}
This is an alternative if you have more data in the same row
function shortRows() {
/* Create a new sheet */
const shortedSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet('shortedSheet')
const range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn())
const values = range.getValues()
/* Short by name */
const result = values.sort((a, b) => {
return a[0].toString().localeCompare(b[0].toString())
})
/* Paste the data in the new sheet */
shortedSheet.getRange(1, 1, result.length, result[0].length).setValues(result)
}
If you don't want to create a new sheet, you have available the methods moveTo
and moveRows
I invite you to test them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.