Skip to content

Instantly share code, notes, and snippets.

@masagrator
Created May 22, 2022 14:53
Show Gist options
  • Save masagrator/d9494d3643609f429892f40df2c6207f to your computer and use it in GitHub Desktop.
Save masagrator/d9494d3643609f429892f40df2c6207f to your computer and use it in GitHub Desktop.
/*
* script to export data in all sheets in the current spreadsheet as individual tsv files
* files will be named according to the name of the sheet
* original author: Michael Derazon
* modifications: MasaGratoR
*/
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "export as tsv files", functionName: "saveAsTSV"}];
ss.addMenu("tsv", csvMenuEntries);
};
function saveAsTSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
// create a folder from the name of the spreadsheet
var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_tsv_' + new Date().getTime());
for (var i = 0 ; i < sheets.length ; i++) {
var sheet = sheets[i];
// append ".tsv" extension to the sheet name
fileName = sheet.getName() + ".tsv";
// convert all available sheet data to tsv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
// create a file in the Docs List with the given name and the tsv data
folder.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++) {
if (data[row][col].toString().indexOf("\t") != -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("\t") + "\r\n";
}
else {
csv += data[row].join("\t");
}
}
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