简体   繁体   中英

Reading multiple spreadsheets in google app script

I'm trying to get all text from a specific cell of all spreadsheets in a folder. My current issue is I can only read them in as a file type which doesn't allow me to access the getRange() function.

Here's my code so far.

function createLog() {

  var folder = DriveApp.getFolderById("id#");//not placing actual id for privacy

  var contents = folder.getFiles();

  var data; //array for relevant text

  var file; 

  var d = new Date();

  var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());



 while(contents.hasNext()) {

    file = contents.next();

     file.getRange("A6");//error is here because it is a file type not a spreadsheet



  }


  for(var i =0; i<contents.length;i++){

log.getRange(0,i).setValue(data[i]); 

  }

}

Once you have the list of files you need to open them with SpreadsheetApp. Then you can work on Spreadsheet using the Sheet and Range functions.

var spreadsheet = SpreadsheetApp.openById(file.getId());
var sheet = spreadsheet.getSheetByName('your sheet name');
var value = sheet.getRange("A6");

See:

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app https://developers.google.com/apps-script/reference/drive/file#getId()

Cameron's answer is correct but I suggest to open spreadsheets by ID instead of names because in Google Drive many files can have the same name... Below is a simplified demo code to test the idea and a few comments to highlight what needs to be adjusted

function createLog() {
  var folder = DriveApp.getFolderById("0B3###############ZMDQ");//not placing actual id for privacy
  var contents = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  var data; //array for relevant text
  var fileID,file,sheet; 
  var data = [];
  var d = new Date();
  var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());

  while(contents.hasNext()) {
    file = contents.next();
    Logger.log('Sheet Name = '+file.getName());
    fileID = file.getId();
    sheet = SpreadsheetApp.openById(fileID).getSheets()[0];// this will get the first sheet in the spreadsheet, adapt to your needs
    data.push([sheet.getRange("A6").getValue()]);// add a condition before this line to get only the data you want
  }
  log.getActiveSheet().getRange(1,1,data.length, data[0].length).setValues(data); 
}

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.

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