How do I to delete/trash/remove a csv file if exists - csv

I'm trying to create an export to csv apps script but it will not delete existing csv files sitting in the same folder. I would like to either trash them or overwrite them.
Here's the code I've already tried
function saveAsCSV() {
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,'_') + '_csv_' + new Date().getTime());
// var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_');
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 file = DriveApp.getFileById(ss.getId());
var folder = file.getParents();
folder = folder.next();
// loop through files and delete ones with existing name
var existingfiles = folder.getFiles()
for (var j = 0 ; j<existingfiles.length;j++){
var existingfile = existingfiles[j].next()
if (existingfile.getName()!=ss.getName()){
//to delete
//existingfile.setTrashed(true);
folder.removeFile(existingfile);
}
}
//create new file
folder.createFile(fileName, csvFile);
}
}
I'd expect all files that don't share the same name as the spreadsheet in that folder to get removed, then a csv for each tab to get created. Instead, I get duplicates of each csv file.

Thanks a lot for you help. The while loop helped a bunch. Here's what worked for me in the end.
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var file = DriveApp.getFileById(ss.getId());
var folder = file.getParents();
folder = folder.next();
// loop through files and delete ones with existing name
var xfiles=folder.getFiles();
while(xfiles.hasNext()) {
var fi=xfiles.next();
if(fi.getMimeType()!=MimeType.GOOGLE_SHEETS){fi.setTrashed(true);}
}
// create new csv files
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);
//create new file
folder.createFile(fileName, csvFile);
}
};

Try this:
function trashOthers() {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var fldr=DriveApp.getFileById(ss.getId()).getParents();
var n=0;
while(fldr.hasNext()) {
var folder=fldr.next();
n++;
}
if(n>1){throw('More than one Folder');}
for (var i=0;i<shts.length;i++) {
var sh=shts[i];
var fileName=sh.getName() + ".csv";
var csvFile=convertRangeToCsvFile_(fileName, sh);
var xfiles=folder.getFiles();
while(xfiles.hasNext()) {
xfiles.next().setTrashed(true);
}
folder.createFile(fileName, csvFile);
}
}
Perhaps this is better:
function deleteOthers() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var shts=ss.getSheets();
var fldr=DriveApp.getFileById(ss.getId()).getParents();
var n=0;
while(fldr.hasNext()) {
var folder=fldr.next();
n++;
}
if(n>1){throw('More than one Folder');}
for (var i=0;i<shts.length;i++) {
var sh=shts[i];
var fileName=sh.getName() + ".csv";
var csvFile=convertRangeToCsvFile_(fileName, sh);
var xfiles=folder.getFiles();
while(xfiles.hasNext()) {
var fi=xfiles.next();
if(fi.getMimeType()!=MimeType.GOOGLE_SHEETS){fi.setTrashed(true);}
}
folder.createFile(fileName, csvFile);
}
}

I used deleteOthers() and trashothers() both are deleting the google form which writes data into csv

Related

Google Spread Sheet Export CSV in the same folder

I am using the script below, working very well (thanks to Ted Bell).
But I need to adapt it because I need the CSV file saved in the same folder as the spreadsheet.
Could you please help me with this matter?
The code below creates a new folder each time on My Drive.
The CSV is ok regarding its name and its format: with semicolon delimiter.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{
name: "export as csv file",
functionName: "saveAsCSV"
}];
ss.addMenu("CSV Export", csvMenuEntries);
var a1 = ss.getRange("A1").getValue();
var name = "MyCompanyName_"+a1;
ss.rename(name);
};
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var sheetname = sheet.getSheetName();
//Logger.log("DEBUG: the name of the spreadsheet is "+ssname);//DEBUG
//Logger.log("DEBUG: the sheet name is "+sheetname);// DEBUG
//// create a folder from the name of the spreadsheet
var folder = DriveApp.createFolder(ssname.toLowerCase() + '_' +
sheetname.toLowerCase().replace(/ /g, '_') + '_csv_' + new Date().getTime());
//Logger.log("DEBUG: the folder name is "+folder);//DEBUG
// append ".csv" extension to the sheet name
var fileName = ssname + '_' + sheetname + ".csv";
// convert all available sheet data to csv format
var csvFile = so_4225484202(fileName);
// create a file in the Docs List with the given name and the csv data
folder.createFile(fileName, csvFile);
Browser.msgBox('Files are waiting in a folder named ' + folder.getName());
}
function isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
function so_4225484202(filename) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var paramsheet = ss.getSheetByName("Parameters");
var linearray = [];
var rowdata = [];
var csv = "";
var fieldvalue = "";
var param = paramsheet.getRange(2, 2, 2);
var paramValues = param.getValues();
//Logger.log("DEBUG: parameters = "+param.getA1Notation());//DEBUG
var fieldDelimiter = paramValues[0][0];
var textDelimiter = paramValues[1][0];
//Logger.log("DEBUG: field delimiter: "+fieldDelimiter+", text delim:
"+textDelimiter);//DEBUG
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
//Logger.log("DEBUG: lastColumn: "+lastColumn+", lastRow: "+lastRow);//DEBUG
// Get array of values in the Data Range
var rangeValues = rangeData.getValues();
// Loop through array and build values for csv
for (i = 0; i < lastRow; i++) {
for (j = 0; j < lastColumn; j++) {
var value = rangeValues[i][j];
var theType = typeof value;
if (theType === "object") {
var testdate = isValidDate(value);
//Logger.log("if typeof is object: testdate: "+testdate);//DEBUG
var testtype = typeof testdate;
if (testtype === "boolean") {
// variable is a boolean
//Logger.log("Its a date");//DEBUG
theType = "date";
} else {
//Logger.log("Its not a date");//DEBUG
}
}
if (theType === "string") {
value = textDelimiter + value + textDelimiter;
}
rowdata.push([value]);
};
//Logger.log("DEBUG: rowdata: "+rowdata);//DEBUG
csv += rowdata.join(fieldDelimiter) + "\n";
var rowdata = [];
};
//Logger.log("DEBUG: csv: "+csv);//DEBUG
return csv;
}
You want to create the CSV file in the same folder of the active Spreadsheet.
You want to achieve this by modifying your script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:
In order to retrieve the folder of the active Spreadsheet, DriveApp.getFileById(ss.getId()).getParents().next() is used for retrieving the folder.
Modified script:
Please modify the function of saveAsCSV() in your script as follows.
From:
var folder = DriveApp.createFolder(ssname.toLowerCase() + '_' + sheetname.toLowerCase().replace(/ /g, '_') + '_csv_' + new Date().getTime());
To:
var folder = DriveApp.getFileById(ss.getId()).getParents().next();
References:
getId()
getFileById()
getParents()
If I misunderstood your question and this was not the direction you want, I apologize.

Copy Sheet to Google Doc

I am trying to copy a table from Google Sheet that includes pictures into a Google doc.
So far I managed to accomplish several things, but not the result that I need.
Source Google Sheet - table with pictures, filled by Importrange formula from another Google sheet.
Copying via appendTable does not copy pictures
I managed to export table to a pdf blob, but couldn't convert it to a regular Google doc then.
Any help appreciated.
function printDocument() {
var source = SpreadsheetApp.getActive();
var spreadsheetId=source.getId();
var sourcesheet = source.getSheetByName('Printable Shooting Plan');
var sheetId = sourcesheet.getSheetId();
var current_lastrow = getLastPopulatedRow(sourcesheet);
var srcData = sourcesheet.getRange('A1:G'+current_lastrow).getValues();
var parents = DriveApp.getFileById(source.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
var doc = DocumentApp.create("Shooting Plan");
var body = doc.getBody();
body.insertParagraph(0, 'Shooting Plan').setHeading(DocumentApp.ParagraphHeading.HEADING1).setAlignment(DocumentApp.HorizontalAlignment.CENTER);
table = body.appendTable(srcData);
table.getRow(0).editAsText().setBold(true);
// Copy doc to the directory we want it to be in. Delete it from root.
var docFile = DriveApp.getFileById(doc.getId());
folder.addFile(docFile);
DriveApp.getRootFolder().removeFile(docFile);
}
function onOpen() {
var submenu = [{name:"Save Doc", functionName:"printDocument"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function getLastPopulatedRow(sheet) {
var data = sheet.getDataRange().getValues();
for (var i = data.length-1; i > 0; i--) {
for (var j = 0; j < data[0].length; j++) {
if (data[i][j]) return i+1;
}
}
return 0;
}

How to export google sheet as CSV by selected columns

I have a Google sheet want to export as CSV file. But there are 2 columns in the sheet I don't want to export.
For example, in the picturecolumn, I don't want to export column "N" and "P"
Here are the Apps Script code I wrote for export
function menu() {
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu('Menu');
var item = menu.addItem('PICC', 'picc');
var item2 = menu.addItem('Export to CSV', 'csv');
item.addToUi();
item2.addToUi()
};
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "Download Primary Time File", functionName: "saveAsCSV"}];
//ss.addMenu("Creating a Timetable", csvMenuEntries);
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu('Menu');
var item = menu.addItem('PICC', 'picc');
var item2 = menu.addItem('Export to CSV', 'csv');
item.addToUi();
item2.addToUi()
};
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("sheet1");
// create a folder from the name of the spreadsheet
var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_' + new Date().getTime());
// append ".csv" extension to the sheet name
fileName = sheet.getName() + ".csv";
// convert all available sheet data to csv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
// create a file in the Docs List with the given name and the csv data
var file = folder.createFile(fileName, csvFile);
//File downlaod
var downloadURL = file.getDownloadUrl().slice(0, -8);
showurl(downloadURL);
}
function showurl(downloadURL) {
var app = UiApp.createApplication().setHeight('60').setWidth('150');
//Change what the popup says here
app.setTitle("Your timetable CSV is ready!");
var panel = app.createPopupPanel()
//Change what the download button says here
var link = app.createAnchor('Click here to download', downloadURL);
panel.add(link);
app.add(panel);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
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 = 1; 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] + "\"";
}
}
// 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);
}
}
As you can see, I used for loop to export the rows and columns, how can I make change to let the two columns not showing in the export CSV
How about this modification?
Modification points :
Modify convertRangeToCsvFile_().
From data retrieved by getValues(), it removes the columns "N" and "P".
In order to reflect this, please modify as follows.
From :
var data = activeRange.getValues();
var csvFile = undefined;
To :
var data = activeRange.getValues();
data = data.map(function(e){return e.filter(function(_, i){return i != 13 && i != 15})}); // Added
var csvFile = undefined;
If I misunderstand your question, please tell me. I would like to modify it.

How to export csv from spreadsheett to drive folder

I have an spreadsheet with 4 sheets that I need in .CSV format. By now, I have a script that sends me the .csv files to my email, but I need to automacally save it into a google drive folder, do you have any ideas ?
This is my actual script:
function Csv(){
var ss = SpreadsheetApp.openById('spreadsheetID');
var url1 = "https://docs.google.com/spreadsheets/d/spreadsheetID/gviz/tq?tqx=out:csv&sheet=Sheet1";
var url2 = "https://docs.google.com/spreadsheets/d/spreadsheetID/gviz/tq?tqx=out:csv&sheet=Sheet2";
var url3 = "https://docs.google.com/spreadsheets/d/spreadsheetID/gviz/tq?tqx=out:csv&sheet=Sheet3";
var url4 = "https://docs.google.com/spreadsheets/d/spreadsheetID/gviz/tq?tqx=out:csv&sheet=Sheet4";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob1 = UrlFetchApp.fetch(url1, params).getBlob();
blob1.setName("File1" +".csv");
var blob2 = UrlFetchApp.fetch(url2, params).getBlob();
blob2.setName("File2" +".csv");
var blob3 = UrlFetchApp.fetch(url3, params).getBlob();
blob3.setName("File3" +".csv");
var blob4 = UrlFetchApp.fetch(url4, params).getBlob();
blob4.setName("File4" +".csv");
MailApp.sendEmail("myemail#gmail.com", "Subject", "Body", {attachments: [blob1,blob2,blob3,blob4]});
}
Thanks!
you can check out the below script. Hope it will help you to manage your sheets as you expected.
/*
* 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: Shotez
*/
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "export as csv files", functionName: "saveAsCSV"}];
ss.addMenu("csv", csvMenuEntries);
};
function saveAsCSV() {
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,'_') + '_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);
// create a file in the Docs List with the given name and the csv 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(",") != -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);
}
}
After running the script just check your google drive for the folder which is containing the .csv files.

Using google script to import .csv files into an existing google sheet. Formatting issues.

Is there a way to not duplicate the headers when the new .csv files are imported from my one drive folder into the existing google sheet? I want the .csv files to be added to the existing sheet in sequential order without adding the headers...example - like row 2 and 19 show. Also, sequential to make the dates go in order in column A. Another question I had was, do you know what happened in line 10? I have deleted and re entered the new data in and every time that happens. This is my script I have now. This is a shareable link to the sheet and what it looks like. https://docs.google.com/spreadsheets/d/1f9HEwikMxm5sJzzRh_-etBxXzL0NpK47i9LtoZVCv_0/edit?usp=sharing This is the script I have right now.
function appendingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
var drng = sht.getDataRange();
var lastRow = drng.getLastRow();
var data = loadFiles();
var dataA =Utilities.parseCsv(data);
if(dataA.length>0)
{
var rng = sht.getRange(lastRow + 1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
else
{
SpreadsheetApp.getUi().alert('No Data Returned from LoadFiles');
}
}
function loadFiles(folderID)
{
var folderID = (typeof(folderID) !== 'undefined')? folderID :
'0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var files = fldr.getFiles();
var s='';
var re = /^.*\.csv$/i;
while (files.hasNext())
{
var file = files.next();
var filename = file.getName();
if(filename.match(re))
{
s += file.getBlob().getDataAsString() + '\n';
file.setName(filename.slice(0,-3) + 'old');
}
}
return s;
}
function createTimeDrivenTriggers() {
// Trigger every Friday at 09:00.
ScriptApp.newTrigger('myFunction')
.timeBased()
.onWeekDay(ScriptApp.WeekDay.FRIDAY)
.atHour(9)
.create();
}
In your loadFiles() script. Try changing it to something like this.
function loadFiles(folderID)
{
//var folderID = (typeof(folderID) !== 'undefined')? folderID : 'Your_folder_id';
var folderID = (typeof(folderID) !== 'undefined')? folderID : 'Your_folder_id';
var fldr = DriveApp.getFolderById(folderID);
var files = fldr.getFiles();
var s='';
var re = /^.*\.csv$/i;
while (files.hasNext())
{
var file = files.next();
var filename = file.getName();
if(filename.match(re))
{
s+=file.getBlob().getDataAsString().split('\n').splice(0,1).join('\n') + '\n';
//s += file.getBlob().getDataAsString() + '\n';
file.setName(filename.slice(0,-3) + 'old');
}
}
return s;
}
You may have to play with this a little. I'm not sure if the last '\n' is needed or not and I'm not that great at chaining so many operations. But you need to remove the headers from each file. You could write a local script that you give to your techs that strips off the headers at the origin and in that case then go back to the way it is now.