google script save range to csv file code example
Example 1: google sheets script save A RANGE to csv
function saveAsCSV() {
var fileName = Browser.inputBox("Save CSV file as (e.g. myCSVFile):");
if (fileName.length !== 0) {
fileName = fileName + ".csv";
var csvFile = convertRangeToCsvFile_(fileName);
DriveApp.createFile(fileName, csvFile, MimeType.CSV);
}
else {
Browser.msgBox("Error: Please enter a CSV file name.");
}
}
function convertRangeToCsvFile_(csvFileName) {
var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection();
try {
var data = ws.getValues();
var csvFile = undefined;
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] + "\"";
}
}
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);
}
}
Example 2: google sheets script save A RANGE to csv
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var searchMenuEntries = [ {name: "Search in all files", functionName: "search"}];
var csvMenuEntries = [{name: "Save as CSV file", functionName: "saveAsCSV"},
{name: "Load from CSV file", functionName: "importFromCSV"}];
ss.addMenu("Search Google Drive", searchMenuEntries);
ss.addMenu("CSV", csvMenuEntries);
}