google-apps-scriptgoogle-sheetsgoogle-drive-api

Write the count files in folder to a spreadsheet


I'm doing a mail merge from a Google sheet, and outputting the PDFs to a Google folder. I'd like to be able to count the files, to ensure that they've all been merged.

I hacked a Google Apps Script:

var sheet = SpreadsheetApp.getActiveSheet();
function countfiles () {
   var folder = DriveApp.getFolderById("1-8Ek9gkm-_-YYYLK5_x7Y3Do_CzvmMfF");  
   var contents = folder.getFiles();
   var i=0;
   var contentsArray = [];
   while (contents.hasNext() && i < 5000) {
     var file = contents.next();
     contentsArray.push(file.getId());  //this is the array that will have the Id's of the first 4999 files.
     i++
   }
      sheet.clear();  
      // Insert Header
      sheet.appendRow("contents")
   }

I'm not sure how to output to my sheet the total count.


Solution

  • Okay, take a look at the Sheet's getRange() and Range's setValue() methods. First, for getRange() we define a range in A1 notation (you can also define it other ways) to get a single cell as a Range object. Then we use the setValue() method on that cell to set the value!

    var sheet = SpreadsheetApp.getActiveSheet();
    function countfiles () {
      var folder = DriveApp.getFolderById("1-8Ek9gkm-_-YYYLK5_x7Y3Do_CzvmMfF");  
      var contents = folder.getFiles();
    
      var i=0;
      var contentsArray = [];
    
      while (contents.hasNext() && i < 5000) {
        var file = contents.next();
        contentsArray.push(file.getId());  //this is the array that will have the Id's of the first 4999 files.
        i++
      }
      sheet.clear();  
    
    
      var range = sheet.getRange("A23"); //Get range object of single cell.
      range.setValue("Number: " + i); //set the value as count (i).
    
      // Insert Header
      sheet.appendRow("contents")
    }