Home > database >  Save to named google drive folder instead of create new folder
Save to named google drive folder instead of create new folder

Time:04-17

I am using the following Script to export a google sheet as a CSV file, but the script creates a new folder with each use, and I need them to always save to the same named folder instead. The folder is currently named "ADP Batches"

Any Suggestions for an edit? The script in question is within the saveAsCSV function. I have posted the entire script:

function saveAsCSV() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet = ss.getSheetByName('Batch');
  // create a folder from the name of the spreadsheet
  var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_'));
  // append ".csv" extension to the sheet name
  fileName = sheet.getName()   ".csv";
  // convert all available sheet data to csv format
  var csvFile = convertRangeToCsvFile_(fileName, sheet);
  // create a file in the Docs List with the given name and the csv data
  var file = folder.createFile(fileName, csvFile);
  //File download
  var downloadURL = file.getDownloadUrl().slice(0, -8);
  showurl(downloadURL);
  
}

function showurl(downloadURL) {
  //Change what the download button says here
  var link = HtmlService.createHtmlOutput('<a href="'   downloadURL   '">Click Here to Download</a>');
  SpreadsheetApp.getUi().showModalDialog(link, 'ADP Pay Data Batch Created!');
}

function convertRangeToCsvFile_(csvFileName, sheet) {
  // get available data range in the spreadsheet
  var activeRange = sheet.getDataRange();
  try {
    var data = activeRange.getValues();
    var csvFile = undefined;

    // loop through the data in the range and build a string with the csv data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row  ) {
        for (var col = 0; col < data[row].length; col  ) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = "\""   data[row][col]   "\"";
          }
        }

        // join each row's columns
        // add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv  = data[row].join(",")   "\r\n";
        }
        else {
          csv  = data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

CodePudding user response:

I used to do it via try/catch.

You can replace the line:

var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_'));

With:

var folder_name = ss.getName().toLowerCase().replace(/ /g,'_');
try { var folder = DriveApp.getFoldersByName(folder_name).next() }
catch(e) { var folder = DriveApp.createFolder(folder_name) }
  • Related