Write Values as a CSV File in Drive

After a nightly sync you often want a dated CSV in Drive without opening Sheets. Build the 2D array, turn it into CSV (reuse valuesToCsv / escapeCsvCell), then create or overwrite a file in a folder and return the File.

What you'll need

  • A 2D values array (often filtered rows + headers)
  • A Drive Folder (see get-or-create folder helpers)
  • The live Convert Sheet Values to CSV Text snippet (valuesToCsv) in the same project

How to use this snippet

function writeValuesAsCsvToDrive(values, folder, filename) { var csv = valuesToCsv(values); var existing = folder.getFilesByName(filename); if (existing.hasNext()) { var file = existing.next(); file.setContent(csv); return file; } return folder.createFile(filename, csv, MimeType.CSV); } // Example: dump "done" rows to Exports/YYYY-MM-DD.csv function exportDoneRowsToDrive() { var ss = SpreadsheetApp.getActive(); var sheet = ss.getSheetByName('Queue'); var values = sheet.getDataRange().getValues(); var headers = values[0]; var statusCol = headers.indexOf('status'); var rows = values.slice(1).filter(function (r) { return String(r[statusCol]).toLowerCase() === 'done'; }); var out = [headers].concat(rows); var folder = getOrCreateFolder(DriveApp.getRootFolder(), 'Exports'); // your helper var name = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd') + '.csv'; var file = writeValuesAsCsvToDrive(out, folder, name); console.log(file.getUrl()); }

Tips

  • Same filename → overwrite content (idempotent nightly). Change the name if you need a history trail.
  • Use getDisplayValues() when you care about how dates look in the CSV.
  • Large exports: stay under Apps Script time limits; batch or archive older CSVs.

Soft tip: search NitroGAS for CSV / Drive helpers, or let Co-Pilot narrate the export function for your ops teammate. Happy Coding.

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension