Need a CSV string for email attachments, Drive dumps, or API uploads? Escape commas/quotes/newlines correctly, then join rows. These two helpers cover the boring part.
What you'll need
- A 2D values array (
getValues()/getDisplayValues()) - Somewhere to put the resulting string (
DriveApp.createFile,MailApp, etc.)
How to use this snippet
function escapeCsvCell(value) {
var s = value == null ? '' : String(value);
if (/[",\n\r]/.test(s)) {
s = '"' + s.replace(/"/g, '""') + '"';
}
return s;
}
function valuesToCsv(values) {
return values.map(function (row) {
return row.map(escapeCsvCell).join(',');
}).join('\n');
}
function exportActiveSheetCsv() {
var sheet = SpreadsheetApp.getActiveSheet();
var csv = valuesToCsv(sheet.getDataRange().getValues());
var file = DriveApp.createFile(sheet.getName() + '.csv', csv, MimeType.CSV);
return file.getUrl();
}
Tips:
- Prefer
getDisplayValues()when you want what users see (formatted dates/currency). - For huge sheets, consider chunking — string building can get heavy.
Happy Coding!
