Convert Sheet Values to CSV Text

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!

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