Apend CSV from gdrive - csv

I am trying to append data from csv saved in google drive to another file in google sheets, I want to ensure that the data gets pasted without the headers. I keep getting an error.
function getCSVAndAppend(spreadsheetId, folderId, filename)
{var folder = DriveApp.getFolderById('1TMFXWDTJpwqTY0JsCefuAean4n9fWIIh');
var files = folder.getFilesByName('Dealers joined data.csv');
var openSpreadsheet = SpreadsheetApp.openById('1E5z7Qd3KRb5geNKlQiYhliYCOtJ0A8ICmZFcUcA1-lI');
var activeSheet = SpreadsheetApp.getActiveSheet();
if ( files.hasNext())\
{var file = files.next();
var csv = file.getBlob().getDataAsString();
var csvData = Utilities.parseCsv(csv);
var csvDataNoHeader = csvData.splice(1,csvData.length-1)
var lastrow = activeSheet.getLastRow();
activeSheet.getRange(lastrow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}

It's possible that there are other issues as noted by Yuri. But this splice looks incorrect to me
var csvDataNoHeader = csvData.splice(1,csvData.length-1)
I think the 1 should be zero and the other parameter should be 1 but it might actually be easier just to use shift to remove the first row. I think csvData is a 2d array.

Related

comma error while importing csv using appscript to google sheets

I am trying to import a csv file to google sheets via google appscript. everything works well except in the last few rows the data is being copied after skipping a row and also it keeps adding more commas to the those empty rows. not sure why. i Have added a test file for reference
https://docs.google.com/spreadsheets/d/1jnzPalCAgO84kxUBrM-aIobIDHu7c99VStJySEyUkKo/edit?usp=sharing
function getCSVAndAppend(spreadsheetId, folderId, filename) {
var folder = DriveApp.getFolderById('1TMFXWDTJpwqTY0JsCefuAean4n9fWIIh');
var files = folder.getFilesByName('Dealers joined data.csv');
var openSpreadsheet = SpreadsheetApp.openById('1E5z7Qd3KRb5geNKlQiYhliYCOtJ0A8ICmZFcUcA1-lI');
var activeSheet = SpreadsheetApp.getActiveSheet();
if (files.hasNext()) {
var file = files.next();
var csv = file.getBlob().getDataAsString();
var csvData = Utilities.parseCsv(csv);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var header = csvData.shift();
var lastrow = activeSheet.getLastRow();
activeSheet.getRange(lastrow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}

How to choose what file to take when using function unzipGmail1(){ in app script

Trying to import a zipped file and choose a certain .CSV inside. How do I ask the script too search for the CSV by name and not number?
function unzipGmail1(){
var threads = GmailApp.search('subject:"XXXXX"');
var message = threads[0].getMessages();
var blobs = message[message.length - 1].getAttachments()[0].copyBlob();
blobs.setContentTypeFromExtension();
var unzippedFile = Utilities.unzip(blobs);
var filename = unzippedFile[0].getName();
var contentType = unzippedFile[0].getContentType();
var csv = unzippedFile['decay vehicle list'];
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XXXX");
var csvData = Utilities.parseCsv();
// Remember to clear the content of the sheet before importing new data
sheet.getRange("A1:AO").clear();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
In that case, how about the following modification?
From:
var unzippedFile = Utilities.unzip(blobs);
var filename = unzippedFile[0].getName();
var contentType = unzippedFile[0].getContentType();
var csv = unzippedFile['decay vehicle list'];
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XXXX");
var csvData = Utilities.parseCsv();
To:
var searchFilename = "###"; // Please set the filename you want to search.
var unzippedFile = Utilities.unzip(blobs);
var blob = unzippedFile.filter(e => e.getName() == searchFilename);
if (blob.length == 0) return;
var csv = blob[0].getDataAsString();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XXXX");
var csvData = Utilities.parseCsv(csv);
In this modification, the file you want to retrieve is retrieved using the filename in blobs. And, when the file blob of the searched filename is existing, the data is retrieved as the string value (CSV data).
References:
filter()
getName()
getDataAsString()

Merge data from specific range of all sheets in a folder to a master sheet

Do I have script that I am trying to get a specific range (single row ie AB2:AB10) from each sheet in a folder (getfolderbyid("jkhkkkkkkk") to copy to a specific master sheet getsheetbyID("lklklkjllj")
this is what I have but it is looping through all 5000 row of the source data sheet so is very slow
///////////////////////////////////////////
function getGaccountsDatafrom() {
var folder = DriveApp.getFolderById("folderID");
var filesIterator = folder.getFiles();
*var file;
var fileType;
var ssID;
var combinedData = [];
var data;
while(filesIterator.hasNext()){
file = filesIterator.next();
fileType = file.getMimeType();
if(fileType ==="application/vnd.google-apps.spreadsheet"){
ssID = file.getId();
data = getDataFromSpreadsheet(ssID);
combinedData = combinedData.concat(data);
} //if end here
}// while ends here
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA");
ws.getRange("A2:AQ").clearContent();
ws.getRange(2, 1, combinedData.length, combinedData[0].length).setValues(combinedData);
}
function getDataFromSpreadsheet(ssID){
var ss=SpreadsheetApp.openById(ssID);
var ws = ss.getSheetByName("DATA");
var data = ws.getRange("CG3:DW3"+ ws.getLastRow()).getValues();
return data;
}////////////////////////////////////////////////////
Hmm... the code is not "looping through all 5000 row of the source data sheet" but iterating files in a folder and getting data from each file separately. That is what makes it run slow, and I do not know if it can be made much faster.
The getDataFromSpreadsheet() function gets too much data because of the superfluous 3 so the result will have blank rows in between. Here is a quick fix:
const data = ws.getRange('CG3:DW' + ws.getLastRow()).getValues();

Exclude final row during csv file dump into google sheet

I am extracting a csv file from my Gmail and dumping it into a Google Sheet using this Google App Script.
But the csv file I am receiving has a 'total' towards the end of it, I would like to load all the data except last row from the csv file i.e., n-1
How do I tweak the below code to such that the code excludes last delimited value
function importfromGmail() {
var sheetName = "Stackoverflow"; // Please set the tab name you want to overwrite the data.
var threads = GmailApp.search("label:Stackoverflow"); // Please set here.
var messages = threads[0].getMessages();
var message = messages[messages.length - 1];
var attachment = message.getAttachments()[0];
var data = [];
Logger.log("ContentType: "+attachment.getContentType())
//Logger.log(Utilities.parseCsv(attachment.getDataAsString(), ","));
data = Utilities.parseCsv(attachment.getDataAsString(), ",");
Logger.log(data.length)
if (data.length > 0) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
Logger.log(SpreadsheetApp.getActiveSpreadsheet().getUrl());
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}
}
In your situation, how about modifying your script as follows?
From:
data = Utilities.parseCsv(attachment.getDataAsString(), ",");
To:
data = Utilities.parseCsv(attachment.getDataAsString(), ",");
data.pop();
By pop(), the last element is removed from data.
Reference:
pop()

Change Google Apps Script from printing array from active cell to specific sheet and range

I'm trying to figure out how to tell the script to print to a specific sheet named 'Creative' and starting in cell B2. Instead of printing to The code, I'm using the code below. Thanks so much for any help you can offer.
function getFileArray(folderId){
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
var fileList = [];
//Loop though files and add names and urls to the array
while (files.hasNext()){
var file = files.next();
var fileName = file.getName();
var fileUrl = file.getUrl();
fileList = fileList.concat([[fileName, fileUrl]]);
}
//See returned fileList in a log
//Logger.log( fileList ) //Preview Returned Array
return fileList
}
//Prints any 2D array to a range that starts with the selected cell
function printArrayToSelection(twoDimArr){
var firstCell = SS.getActiveCell();
var lastCell = firstCell.offset(twoDimArr.length - 1, twoDimArr[0].length - 1);
var destinationRange = SS.getActiveSheet().getRange(
firstCell.getA1Notation() + ':' + lastCell.getA1Notation());
destinationRange.setValues(twoDimArr);
}
//Print the actual data
function printFileArray(){
printArrayToSelection(getFileArray('FOLDERIDHERE'));
}
To specify the sheet for the destination range, you can use the getSheetByName method and pass "Creative" as an argument.
To get the destination range, I would recommend using the getRange method and passing the row, column, number of rows, and number of columns as arguments. For your case, this would be 2, 2, twoDimArr.length, twoDimArr[0].length
The documentation for this method can be found here:
https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(Integer,Integer,Integer,Integer)
function printArrayToSelection(twoDimArr){
var firstCell = SS.getActiveCell();
var lastCell = firstCell.offset(twoDimArr.length - 1, twoDimArr[0].length - 1);
var destinationRange = SS.getSheetByName("Creative").getRange(2, 2, twoDimArr.length, twoDimArr[0].length);
destinationRange.setValues(twoDimArr);
}