Looping through multiple google spreadsheets with google scripts

旧城冷巷雨未停 提交于 2020-12-26 04:35:20

问题


So I have multiple different spreadsheets inside of google drive (completely different files, not in the same file and different sheets), and I've been trying to figure out a way to pull data from all of the spreadsheets and populate one main sheet. But the problem I've been trying to figure out is that I can't seem to find a way to loop through all the spreadsheets.

I've read a suggestion on another similar question in which they said to create a different spreadsheet that stored all the spreadsheet id's inside of it. But my other problem is I won't know how many spreadsheets there are when I run the application because more are added all the time.

So, since their doesn't seem to be a way to loop through all the spreadsheets in your drive, is their a way in google scripts to make it so that anytime a file is created, the script runs and is able to obtain the newly created file id?

Thanks, Ethan.


回答1:


Google Sheets have a MIME type of:

application/vnd.google-apps.spreadsheet

You can loop through all the files in your drive and log the MIME types of all the files, just to see what different MIME types might be:

function getAllSheets() {
 // Log the name of every file in the user's Drive.
 var files = DriveApp.getFiles();
   while (files.hasNext()) {
     var file = files.next();
     Logger.log(file.getMimeType());
 }
};

You can get all files by a certain MIME type. This code prints the names of all the spreadsheets in your drive to the LOG.

function getAllSheets() {
 // Log the name of every file in the user's Drive.
 var files = DriveApp.getFilesByType("application/vnd.google-apps.spreadsheet")
   while (files.hasNext()) {
     var file = files.next();
     Logger.log(file.getName());
 }
};

So, you can iterate through all the spreadsheets in your drive, or in a specific folder.




回答2:


All google drive files

List all files using "Google Apps Script - Drive API"

// Log the name of every file in the user's Drive.
var files = DriveApp.getFiles();
while (files.hasNext()) {
  var file = files.next();
  Logger.log(file.getName());
}

From the example at the top: https://developers.google.com/apps-script/reference/drive/

getMimeType()

Look if the method exists. If obj.getMimeType===undefined its a folder. or, to make it more robust in case the api changes (adds the method to folders), use if (obj.getMimeType===undefined || obj.getMimeType().toLowerCase() =="application/vnd.google-apps.folder")

From How can I discriminate between file and folder in DriveApp using GAS



来源:https://stackoverflow.com/questions/27537807/looping-through-multiple-google-spreadsheets-with-google-scripts

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