cgrouge
cgrouge

Reputation: 177

Google App Script to export and replace csv files

I currently have a google spreadsheet that will create a csv file and save it on my google drive when the trigger goes off. What I can't figure out is how to delete the existing csv file before creating a new csv file. When it saves the new version, it simply makes another copy. I need to overwrite the previous file (or delete the old one then export/write the new version.)

Here is the script to create the csv file:

function saveAsCSV() {
  // Prompts the user for the file name
  var fileName = ("myCSVFile");
  // Check that the file name entered wasn't empty
  if (fileName.length !== 0) {
    // Add the ".csv" extension to the file name
    fileName = fileName + ".csv";
    // Convert the range data to CSV format
    var csvFile = convertRangeToCsvFile_(fileName);
    // Create a file in the Docs List with the given name and the CSV data
    DriveApp.createFile(fileName, csvFile);
  }
  else {
    Browser.msgBox("Error: Please enter a CSV file name.");
  }
}

How can I overwrite the csv file every time the script trigger goes off?

Upvotes: 0

Views: 2667

Answers (2)

rmhunter
rmhunter

Reputation: 581

You can either delete the file first, using File.setTrashed(true);, or you can simply change the contents of the file, using File.setContent(csvFile);

Upvotes: 1

Tiffany G. Wilson
Tiffany G. Wilson

Reputation: 573

You can delete the file before writing the new one using file.setTrashed(true). See the lead example in the File Class documentation.

Upvotes: 1

Related Questions