繁体   English   中英

如何匹配 Google Drive 和 Google Sheets 中的字母数字顺序?

[英]How to match alphanumerical order in both Google Drive and Google Sheets?

在我的 Google Drive 上,我有一个包含 2006 个文件的文件夹。 这些文件按名称排序。 (从 A -> Z)这是我文件夹中文件的确切顺序: https ://gist.github.com/cuzureau/a36deb8e02ab0f2e0523cd58f2cf0950

现在,我还有一个 Google 表格,其中的文件名写在一个列中。 每个单元格一个文件名。 它们按字母顺序(从 A -> Z)这是列内文件的确切顺序: https ://gist.github.com/cuzureau/6fe722b821ce3aa60b697819b64d6b05

文件名的排序顺序不同。 我怎样才能做到这一点 ?

也许我应该使用 Google 表格中的公式重新排序列中的文件名?

以下是使用 Google Apps 脚本的两种可能的解决方案(均使用前 100 个文件进行了测试):

直接使用 DriveApp 获取名称

  1. 输入您的工作表,然后单击Extensions > Apps Script 在此处输入图像描述
  2. 复制文件所在的文件夹 ID
  3. 复制此脚本。
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)
}

Short 直接创建新工作表

如果您在同一行中有更多数据,这是一种替代方法

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)
}

如果您不想创建新工作表,您可以使用moveTomoveRows方法,我邀请您进行测试。

文档:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM