Skip to content

Instantly share code, notes, and snippets.

@leonardonormando
Forked from mderazon/export-to-csv.gs
Last active March 31, 2017 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardonormando/0d4af902899cedeb66035185569279fd to your computer and use it in GitHub Desktop.
Save leonardonormando/0d4af902899cedeb66035185569279fd to your computer and use it in GitHub Desktop.
Google apps script to export to individual csv files all sheets in an open spreadsheet
// From http://stackoverflow.com/questions/1353684
// Returns 'true' if variable d is a date object.
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
// Test if value is a date and if so format
// otherwise, reflect input variable back as-is.
function isDate(sDate) {
if (isValidDate(sDate)) {
sDate = Utilities.formatDate(new Date(sDate), 'GMT-3', "dd MMM yy HH:mm");
}
return sDate;
}
/*
* script to export data in all sheets in the current spreadsheet as individual csv files
* files will be named according to the name of the sheet
* author: Michael Derazon
*/
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "Exportar como CSV", functionName: "saveAsCSV"}];
ss.addMenu("FormaVendas", csvMenuEntries);
};
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
//var sheets = ss.getSheetByName("RDFLojas");
var sheets = ss.getSheets();
// create a folder from the name of the spreadsheet
var folderX = DriveApp.getFolderById("0B31DH_UoT9V7NF9nLUNXRldlS1k");
//var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_' + new Date().getTime());
for (var i = 0 ; i < sheets.length ; i++) {
var sheet = sheets[i];
// append ".csv" extension to the sheet name
fileName = sheet.getName() + ".csv";
// convert all available sheet data to csv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
var files = DriveApp.getFilesByName(fileName);
while (files.hasNext()) {
var file = files.next();
if (new Date() - file.getLastUpdated() > 1000) {
file.setTrashed(true);
}
}
// create a file in the Docs List with the given name and the csv data
folderX.createFile(fileName, csvFile);
}
//Browser.msgBox('Files are waiting in a folder named ' + folder.getName());
}
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
data[row][col] = isDate(data[row][col]); // Format, if date
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment