Search code examples
google-apps-scriptgoogle-sheetsgoogle-drive-api

How to update or overwrite existing sheets


I have 99% of this done. What it is already doing is combining 6-7 CSV files from two folders and putting them all into one Google Sheet Workbook. However, these files are update daily so as you can imagine I need to update/overwrite the Google Sheet Workbook also. Just can't figure out how to implement it into my already working code. Appreciate the help in advance.

Do I update, delete sheet, etc? I will of course add a timing trigger at the end of it to work correctly.

Error: 10:13:16 AM Error
Exception: A sheet with the name "Employee Basic Summary with Supv.csv" already exists. Please enter another name. loadCSVFilesIntoSheets @ googlesheets.gs:10

ERROR IMAGE

CODE:

function loadCSVFilesIntoSheets() { 
  var ss=SpreadsheetApp.openById('CURRENTLY USING THIS FOR GOOGLE WORKBOOK 'ID' AND WORKING');
  var folder=DriveApp.getFolderById('1ST CSV FOLDER 'ID' WORKING FINE');
  var folder=DriveApp.getFolderById('2ND CSV FOLDER 'ID' WORKING FINE');
  var files=folder.getFilesByType(MimeType.CSV);
  while(files.hasNext()) {
    var file=files.next();
    var vA=Utilities.parseCsv(file.getBlob().getDataAsString());
    var sh=ss.insertSheet(file.getName());
    sh.getRange(1,1,vA.length,vA[0].length).setValues(vA);
  }
}

Solution

  • Try this:

    function loadCSVFilesIntoSheets() {
      var ss = SpreadsheetApp.openById('ssid');
      const ids = ["id1", "id2"];
      ids.forEach(id => {
        let folder = DriveApp.getFolderById(id);
        var files = folder.getFilesByType(MimeType.CSV);
        while (files.hasNext()) {
          var file = files.next();
          let shts = ss.getSheets().map(sh => sh.getName());
          var vA = Utilities.parseCsv(file.getBlob().getDataAsString());
          let idx = shts.indexOf(file.getName());
          let sh;
          if (!~idx) {
            sh = ss.insertSheet(file.getName());
          } else {
            sh = ss.getSheetByName(shts[idx]);
            sh.clearContents();//Since this add's a legend to each entry with sheet name, and new Date() you could put a routine to remove some sections based upon date somewhere around here
          }
          sh.getRange(sh.getLastRow() + 1, 1, 1, 2).setValues([["Sheet Name:", sh.getName(),new Date()]]);
          sh.getRange(sh.getLastRow() + 1, 1, vA.length, vA[0].length).setValues(vA);
        }
      });
    }