Search code examples
google-apps-scriptgoogle-sheets

Get data from newest files in a Google Drive Folder to another Google Spreadsheet in the same folder


I use an app to export some date to a Google Drive Folder, every time my app runs, it exports a CSV to a specific folder in Google Drive. I would need help to be able to automate the process and more precisely: the data from the newest CSV export to be automatically taken over by another file (MASTER-SHEET) located in the same folder.

I try some functions in Apps Script but I am new on this and some help from you are necessary.

I also try this script:

function importData()
{
  var ss = SpreadsheetApp.openById("{MASTERSHEET_ID}");
  var folderID = '{GOOGLE_DRIVE_FOLDER_ID}';
  var fldr = DriveApp.getFolderById(folderID);
  var files = fldr.getFilesByType('text/csv');
  while (files.hasNext())
  {
    var file = files.next();
    var fileName = file.getName();
    if(file.getBlob().getContentType() === "text/csv" && !fileName.match(/.old/))
    {
      var csvstr=file.getBlob().getDataAsString();
      var csvData=Utilities.parseCsv(csvstr);
      var sheet = ss.getSheetByName("MASTERSHEET_SHEET1");
    }
  }
}

After i hit run I dont get any error, but also no result in the Sheet1 of the MasterSheet.

Thanks!


Solution

  • function findMostRecentCsv() {
      const fldr = DriveApp.getFolderById(gobj.globals.gpstracksfolderid);//change folderid
      const files = fldr.getFilesByType(MimeType.CSV);
      const fA = [];
      while(files.hasNext()) {
        fA.push(files.next())
      }
      fA.sort((a,b)=> {
        return b.getDateCreated().valueOf() - a.getDateCreated().valueOf()
      })
      Logger.log(fA[0].getName());
      return fA[0];
    }
    
    function loadCSVInSpreadsheet() {
      const ss = SpreadsheetApp.openById(gobj.globals.ssid);//change id to destination spreadsheet
      const sh = ss.getSheetByName("Sheet0");//change name to dest sheet
      sh.clearContents();//not sure if  you will want this
      const csv = findMostRecentCsv().getBlob().getDataAsString();
      const a = Utilities.parseCsv(csv);
      sh.getRange(1,1,a.length,a[0].length).setValues(a);
    
    }