保存到命名为 google 的驱动器文件夹而不是创建新文件夹

Save to named google drive folder instead of create new folder

我正在使用以下脚本将 google sheet 导出为 CSV 文件,但脚本每次使用都会创建一个新文件夹,我需要它们始终保存到同一个文件夹命名的文件夹。该文件夹当前名为“ADP Batches”

有任何修改建议吗?有问题的脚本在 saveAsCSV 函数中。我已经发布了整个脚本:

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);
  }
}

我以前是通过 try/catch 完成的。

您可以替换行:

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

与:

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