Get all the ID of the files

非 Y 不嫁゛ 提交于 2020-12-15 06:42:29

问题


I'm working on a folder per grade level with the same content. I used the IMPORT RANGE function to connect the spreadsheets. So I need to update the IDs every time I create another grade level. May I ask if it is possible for me to get all the IDs of all the files that I'm working on without editing or typing them one by one? Maybe a script that can make it easier?

Here's the picture of the list of IDs.

If it is possible, the flow I’m thinking of is to get the filename of the files and then get the id of it.


回答1:


Explanation:

  • The following script will get all the file names in the range B3:B. Then forEach file name we use getFilesByName to get the files corresponding to that name. Make sure you don't have files with the same name, otherwise this process will return multiple IDs for the same name and therefore the logic won't work.

  • Finally we use getId to get the ID of each file and store it into an array. This array will be then pasted to column C starting from cell C3 as you indicate in the screenshot.

Solution:

function myFunction() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1'); // change that to the name of your sheet
  const filenames = sh.getRange('B3:B').getValues().flat().filter(r=>r!='');
  const IDs = [];
  const folderId = "put your folder id here";
  const Folder=DriveApp.getFolderById(folderId);
  filenames.forEach(fn=>{
      let Files = Folder.getFilesByName(fn);
      while(Files.hasNext()){
          let file = Files.next();
          IDs.push([file.getId()]);
      }
  });
  sh.getRange(3,3,IDs.length,1).setValues(IDs);
}


来源:https://stackoverflow.com/questions/64924925/get-all-the-id-of-the-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!