Downloading a PDF version of the open spreadsheet in Google Drive via scripts - google-apps-script

I've been reading up on how to save a spreadsheet to PDF via Google Docs Scripting. Most suggestions I've come across reference using something like:
theOutputFile.saveAndClose();
DocsList.createFile(theOutputFile.getAs('application/pdf')).rename(theOutputName+".pdf");
That is, they reference the saveAndClose() function. I don't want to save or close my spreadsheet - but I do want to download the current sheet as a PDF.
Any suggestions? Thanks.

For saving the current sheet as a PDF, you can hide all the other sheets, save the current, & then show all sheets again.
The pdf creation might start before the end of the sheets' hiding and then will include 2 sheets - the current & the last sheets - in the pdf file.
Adding a sleep or a confirmation msgbox, between showOneSheet & createPdf eliminated the problem.
This answer is a variation of Marco Zoqui's answer: "To send a single sheet you may hide all other before sending" in Google Apps Script to Email Active Spreadsheet
var sheet = SpreadsheetApp.getActiveSheet();
var sheetToSave = sheet.getName();
showOneSheet(sheetToSave);
Utilities.sleep(2000);
createPdf("TestFolder", "TestPDF");
showAllSheets();
function showOneSheet(SheetToShow) {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i in sheets){
if (sheets[i].getName()==SheetToShow){
sheets[i].showSheet();
}
else {
sheets[i].hideSheet();
}
}
}
function showAllSheets() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i in sheets){
sheets[i].showSheet();
}
}
function createPdf(saveToFolder, fileName){
var ssa = SpreadsheetApp.getActiveSpreadsheet();
var pdf = ssa.getAs("application/pdf");
try {
var folder = DocsList.getFolder(saveToFolder);
}
//Create Folder if not exists
catch(error){
folder = DocsList.createFolder(saveToFolder);
}
var file = folder.createFile(pdf);
file.rename(fileName);
return file;
}

I was able to get it to work using #hsgv's answer, however, this is the version I ended up using based on this.
// global save to folder variable:
var folderName = "My/Special/Folder";
function createInvoiceInGoogleDrive(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
// getting some values from the spreadhseet for the file name
var invoiceNumber = sheet.getRange("E3").getValue();
var vendor = sheet.getRange("A9").getValue();
var fileName = invoiceNumber + ' - ' + vendor + " - Invoice.pdf";
var pdfBlob = sheetToPDF(spreadsheet, sheet);
pdfBlob.setName(fileName);
var folder = getOrCreateFolder(folderName);
var matchingFileList = folder.find(fileName);
if ( matchingFileList.length > 0 ) {
Browser.msgBox("ERROR: New invoice not created. " + fileName + " already exists at " + folderName);
return false;
} else {
var f = folder.createFile(pdfBlob);
spreadsheet.toast('Created a new invoice on Google Drive!');
return true;
}
}
// thanks: https://gist.github.com/gregorynicholas/9008572
function sheetToPDF(spreadsheet, sheet) {
var ssID = spreadsheet.getId();
var gid = sheet.getSheetId();
// &gid=x at the end of above url if you only want a particular sheet
var url2 = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID +
"&gid=" + gid +
"&fmcmd=12&size=7&fzr=true&portrait=true&fitw=true&locale=en&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=true";
// AUTH TOKEN required to access the UrlFetchApp call below. You can receive it
// from https://appscripts.appspot.com/getAuthToken
var AUTH_TOKEN = "{GET YOUR OWN AUTH TOKEN}";
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url2, {headers: {Authorization: auth}}).getBlob();
return res;
}
/**
* Get or create a folder based on its name/path
*/
function getOrCreateFolder(folderName) {
try {
var theFolder = DocsList.getFolder(folderName);
} catch(error){
var theFolder = DocsList.createFolder(folderName);
}
return theFolder;

Related

I want to change the names of old files uploaded to Google Forms

I have a google form and all the files uploaded by the participants contain random names.
The data is summarized in personal photos, ID photos, photos of certificates.
That is why we want to name the files with the names of the people themselves by choosing a specific field.
I tried in a code via the google apps script to change the names but it is no more than 70 to 80 files and then it stops
Is there a code that will help me with this work, especially since the number of files is large?
function renamefile() {
var form = FormApp.openById('16aPNgaSuDZ-e0ibw08jW7_-YMULGWV-_iUP9uQHE'); //DDD
var formResponses = form.getResponses();
var baseString = 'https://drive.google.com/file/d/';
var endString = '/view?usp=drivesdk';
var folder = DriveApp.getFolderById('1BPA7wkECV1vOB6bo3tGfUZd9MifjwYJG2BVI_sHSeNojFY-xiN4dvLW_vc2zw4IEe');
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var photoID = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO" ;
var url = baseString + photoID + endString;
var urlCheck = file.getUrl();
if ( url == urlCheck) {
var modName = newName + ".pdf" ;
file.setName(modName);
}
}
}
}
Modification points:
From your showing script, it seems that the form responses are retrieved every loop of the "while loop". I thought that this might be a high process cost.
From your script, it seems that you want to rename PDF files. In this case, when PDF files are retrieved. The process cost might be able to be reduced.
I thought that in your situation, the file ID can be used for checking the file instead of URL.
When these points are reflected in your script, how about the following modification?
Modified script:
function renamefile() {
var form = FormApp.openById('###'); // Please set your file ID of Google Forms.
var folder = DriveApp.getFolderById('###'); // Please set your folder ID.
// Create an object for searching file ID.
var obj = form.getResponses().reduce((o, f) => {
var itemResponses = f.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var fileId = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO";
o[fileId] = newName + ".pdf";
return o;
}, {});
// Rename files.
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
if (obj[fileId]) {
file.setName(obj[fileId]);
}
}
}
When this script is run, first, an object is created. This object is used for searching the file ID in the folder. And, using the object, the PDF files in the folder are renamed.
Note:
If your files are not PDF files, please modify var files = folder.getFilesByType(MimeType.PDF); to var files = folder.folder.getFiles();.
When the number of files is large and the processing time is over 6 minutes, I would like to propose using the batch requests. The sample script of batch request can be seen at this thread. And, when the above script is modified, the sample script is as follows. When you use this script, please enable Drive API at Advanced Google services. And also, please install a Google Apps Script library of BatchRequest. Ref
function renamefile2() {
var form = FormApp.openById('###'); // Please set your file ID of Google Forms.
var folderId = "###"; // Please set your folder ID.
// Create an object for searching file ID.
var obj = form.getResponses().reduce((o, f) => {
var itemResponses = f.getItemResponses();
var itemResponseFname = itemResponses[1];
var itemResponsePhoto = itemResponses[15];
var fileId = itemResponsePhoto.getResponse();
var newName = itemResponseFname.getResponse() + " - " + "PHOTO";
o[fileId] = newName + ".pdf";
return o;
}, {});
// Rename files using batch request.
var { items } = Drive.Files.list({ q: `'${folderId}' in parents and trashed=false and mimeType='${MimeType.PDF}'`, maxResults: 1000, fields: "items(id)" });
var requests = items.reduce((ar, { id }) => {
if (obj[id]) {
ar.push({
method: "PATCH",
endpoint: `https://www.googleapis.com/drive/v3/files/${id}`,
requestBody: { name: obj[id] },
});
}
return ar;
}, []);
var result = BatchRequest.EDo({ batchPath: "batch/drive/v3", requests });
}
In this sample, it supposes that the number of your files is less than 1000. When the number of files is more than 1000, please retrieve all files using pageToken.
Reference:
reduce()

Is there a way to auto next ( to the next item) the in cell data validation dropdown list after running a script in google sheet?

I am currently new to the google sheet script. I'm doing a simple report generator in google sheet using script. I already have a script that saves a generated pdf file to the google drive. In my google sheet there is a cell referenced to the main data source with dropdown data validation selecting the email of the person and will generate the other details (it a reference also based from that email in the same sheet). what I want is, when I run the script to save pdf file, it should automatically generate pdf file for each item in the dropdown validation list. Is this possible? Anyone who know this please.
this is my code that generate pdf file to the drive (i got this also from the net and made some changes)... thank you so much in advance.
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet2 = ss.getSheetByName('ID');
var gdid1 = sheet2.getRange('B1').getValue();
var gdid2 = sheet2.getRange('B4').getValue();
function onOpen() {
var ui = SpreadsheetApp.getUi()
ui.createMenu('ExportGDrive')
.addItem('Export BasicED', 'exportBasicED')
.addItem('Export College', 'exportCollege')
.addToUi()
}
function _exportBasic(blob, fileName, spreadsheet) {
blob = blob.setName(fileName)
var folder = DriveApp.getFolderById(gdid1)
var pdfFile = folder.createFile(blob)
// Display a modal dialog box with custom HtmlService content.
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open ' + fileName + '</p>')
.setWidth(300)
.setHeight(80)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful')
}
function _exportCollege(blob, fileName, spreadsheet) {
blob = blob.setName(fileName)
var folder = DriveApp.getFolderById(gdid2)
var pdfFile = folder.createFile(blob)
// Display a modal dialog box with custom HtmlService content.
const htmlOutput = HtmlService
.createHtmlOutput('<p>Click to open ' + fileName + '</p>')
.setWidth(300)
.setHeight(80)
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Export Successful')
}
function exportAsPDF() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var blob = _getAsBlob(spreadsheet.getUrl())
_exportBlob(blob, spreadsheet.getName(), spreadsheet)
}
function _getAsBlob(url, sheet, range) {
var rangeParam = ''
var sheetParam = ''
if (range) {
rangeParam =
'&r1=' + (range.getRow() - 1)
+ '&r2=' + range.getLastRow()
+ '&c1=' + (range.getColumn() - 1)
+ '&c2=' + range.getLastColumn()
}
if (sheet) {
sheetParam = '&gid=' + sheet.getSheetId()
}
// A credit to https://gist.github.com/Spencer-Easton/78f9867a691e549c9c70
// these parameters are reverse-engineered (not officially documented by Google)
// they may break overtime.
var exportUrl = url.replace(/\/edit.*$/, '')
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=LETTER'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.75'
+ '&bottom_margin=0.75'
+ '&left_margin=0.7'
+ '&right_margin=0.7'
+ '&sheetnames=false&printtitle=false'
+ '&pagenum=UNDEFINED' // change it to CENTER to print page numbers
+ '&gridlines=FALSE'
+ '&fzr=FALSE'
+ sheetParam
+ rangeParam
Logger.log('exportUrl=' + exportUrl)
var response
var i = 0
for (; i < 5; i += 1) {
response = UrlFetchApp.fetch(exportUrl, {
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
})
if (response.getResponseCode() === 429) {
// printing too fast, retrying
Utilities.sleep(3000)
} else {
break
}
}
if (i === 5) {
throw new Error('Printing failed. Too many sheets to print.')
}
return response.getBlob()
}
function exportCurrentSheetAsPDF() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var currentSheet = SpreadsheetApp.getActiveSheet()
// Change the Cell for the name of the file (example: B3 for current sheet)
var blob = _getAsBlob(spreadsheet.getUrl(), currentSheet)
_exportBlob(blob, SpreadsheetApp.getActiveSheet().getRange('B3').getValue(), spreadsheet)
}
function exportBasicED() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet1 = spreadsheet.getSheetByName('Generate-Basic Ed');
var name = sheet1.getRange('B3').getValue();
// Change the Cell for the name of the file (example: B3 for current sheet)
var blob = _getAsBlob(spreadsheet.getUrl(), sheet1)
_exportBasic(blob, name, spreadsheet)
}
function exportCollege() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet1 = spreadsheet.getSheetByName('Generate-College');
var name = sheet1.getRange('B3').getValue();
// Change the Cell for the name of the file (example: B3 for current sheet)
var blob = _getAsBlob(spreadsheet.getUrl(), sheet1)
_exportCollege(blob, name, spreadsheet)
}
Try
function nextItem() {
var sh = SpreadsheetApp.getActive();
var data = sh.getRange('myValidationList').getValues();
for (var i = 0; i < data.length; i++) {
sh.getRange('A2').setValue(data[i][0]);
SpreadsheetApp.flush();
// here you can call the script to send pdf
Utilities.sleep(1000);
}
};
assuming that myValidationList is the list of valid data, avd A2 the cell in wich the validation applies.

Create backup of spreadsheet with values and format only in specific subfolder

I have been trying to combine two scripts to create a script that i can run on demand by using a custom menu. I would like the script to do the following:
Make a copy with values and format only (no formulas and importrange), of a existing spreadsheet.
Name the copy the same as the original spreadsheet + timestamp in "yyyy-mm-dd" format.
Place the copy in a specific subfolder.
Also to be able to create the copy on demand, using a custom menu button to do so.
And lastly to have a custom menu button for easy access to said subfolder.
So far i have found two scripts that can do parts of this task but have not been able to combine them to a single script. Is this possible?
See the code below for the two scripts:
SCRIPT 1
// Program: Archive GSheet with Date Stamp
// Programmer: Michael Fryar
// Date: 19 September 2017
// Google Apps Script to copy Google Sheet to subfolder with date stamp in name
// Add Custom Menu
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Archive')
.addItem('Archive a copy with timestamp', 'archiveCopy')
.addItem('Open folder', 'openArchive')
.addToUi();
}
// Define function to copy sheet to subfolder with date stamp in name
// Building on https://gist.github.com/abhijeetchopra/99a11fb6016a70287112
function archiveCopy() {
// Replace "spreadsheetId" with the ID of the Google Sheet you wish to copy
var file = DriveApp.getFileById("ID")
// Replace "folderId" with the ID of the folder where you want the copy saved
var destination = DriveApp.getFolderById("ID");
// Get timezone for datestamp
var timeZone = Session.getScriptTimeZone();
// Generate datestamp and store in variable formattedDate as year-month-date
var formattedDate = Utilities.formatDate(new Date(), timeZone , "yyyy-MM-dd");
// Replace "file_name" with the name you want to give the copy
var name = formattedDate + " Copy";
// Archive copy of "file" with "name" at the "destination"
file.makeCopy(name, destination);
}
// Define function to open archive folder in new tab
// Building on https://www.youtube.com/watch?v=2y7Y5hwmPc4
function openArchive() {
// Replace "folderId" with the ID of the folder where you want copies saved
var url = "https://drive.google.com/drive/folders/"
// HTML to open folder url in new tab and then close dialogue window in sheet
var html = "<script>window.open('" + url + "');google.script.host.close();</script>";
// Push HTML into user interface
var userInterface = HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Opening Archive Folder');
}
SCRIPT 2
function copyEntireSpreadsheet() {
var id = "ID"; // Please set the source Spreadsheet ID.
var ss = SpreadsheetApp.openById(id);
var srcSheets = ss.getSheets();
var tempSheets = srcSheets.map(function(sheet, i) {
var sheetName = sheet.getSheetName();
var dstSheet = sheet.copyTo(ss).setName(sheetName + "_temp");
var src = dstSheet.getDataRange();
src.copyTo(src, {contentsOnly: true});
return dstSheet;
});
var destination = ss.copy(ss.getName() + " - " + new Date().toLocaleString());
tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
var dstSheets = destination.getSheets();
dstSheets.forEach(function(sheet) {
var sheetName = sheet.getSheetName();
if (sheetName.indexOf("_temp") == -1) {
destination.deleteSheet(sheet);
} else {
sheet.setName(sheetName.slice(0, -5));
}
});
}
UPDATE!
I found another script that could do the parts that i needed and was finally able to combine them together. Posting script below to benefit others in search of something similar:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Archive')
.addItem('Archive copy with timestamp', 'Archive')
.addItem('Open folder', 'openArchive')
.addToUi();
}
function Archive() {
var spreadsheetId = "###"; // Please set the source Spreadsheet ID.
var destFolderId = "###"; // Please set the destination folder ID.
// Copy each sheet in the source Spreadsheet by removing the formulas as the temporal sheets.
var ss = SpreadsheetApp.openById(spreadsheetId);
var tempSheets = ss.getSheets().map(function(sheet) {
var dstSheet = sheet.copyTo(ss).setName(sheet.getSheetName() + "_temp");
var src = dstSheet.getDataRange();
src.copyTo(src, {contentsOnly: true});
return dstSheet;
});
// Get timezone for datestamp
var timeZone = Session.getScriptTimeZone();
// Generate datestamp and store in variable formattedDate as year-month-date
var formattedDate = Utilities.formatDate(new Date(), timeZone , "yyyy-MM-dd");
// Copy the source Spreadsheet.
var destination = ss.copy(ss.getName() + " " + formattedDate);
// Delete the temporal sheets in the source Spreadsheet.
tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
// Delete the original sheets from the copied Spreadsheet and rename the copied sheets.
destination.getSheets().forEach(function(sheet) {
var sheetName = sheet.getSheetName();
if (sheetName.indexOf("_temp") == -1) {
destination.deleteSheet(sheet);
} else {
sheet.setName(sheetName.slice(0, -5));
}
});
// Move file to the destination folder.
var file = DriveApp.getFileById(destination.getId());
DriveApp.getFolderById(destFolderId).addFile(file);
file.getParents().next().removeFile(file);
}
// Define function to open archive folder in new tab
// Building on https://www.youtube.com/watch?v=2y7Y5hwmPc4
function openArchive() {
// Replace "folderId" with the ID of the folder where you want copies saved
var url = "https://drive.google.com/drive/folders/folderid"
// HTML to open folder url in new tab and then close dialogue window in sheet
var html = "<script>window.open('" + url + "');google.script.host.close();</script>";
// Push HTML into user interface
var userInterface = HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Opening Archive Folder');
}

Google script save / update file

I am again creating a simple script to save a daily menu cart. Aim is, that the file (PDF) can be shared with a static link. Base for the PDF is a Google spreadsheet.
Currently I have the following code:
// Add new menu to sheet
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [
{name: "Speichern", functionName: "savepdf"},
];
spreadsheet.addMenu("Als PDF speichern", entries);
};
// Add function to save sheet as PDF
function savepdf () {
// Get spreadsheet file
var fileid = 'FILEIDGOESHERE';
// Create date for file name
var ss = SpreadsheetApp.openById(fileid);
var name = ss.getName();
var sheet = ss.getSheetByName('Tageskarte');
var range = sheet.getRange(12,1);
var d = range.getValue();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var theDate = curr_year + "-" + curr_month + "-" + curr_date + "-";
var namearchive = "Tageskarte-"+ theDate +".pdf";
var name = "Tageskarte-Allweglehen.pdf";
// Choose folder where PDFs are saved
var foldersave=DriveApp.getFolderById('FOLDERIDGOESHERE');
var foldersavearchive=DriveApp.getFolderById('FOLDERIDGOESHERE');
// OAuth
var request = {
"method": "GET",
"headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
"muteHttpExceptions": true
};
// Create PDF + update current file
var fetch='https://docs.google.com/spreadsheets/d/'+fileid+'/export?format=pdf&size=A4&portrait=true&gridlines=false'
var pdf = UrlFetchApp.fetch(fetch, request);
pdf = pdf.getBlob().getAs('application/pdf').setName(name);
var file = foldersave.createFile(pdf);
// Create PDF for archive and save
var pdfarchive = UrlFetchApp.fetch(fetch, request);
pdfarchive = pdfarchive.getBlob().setName(namearchive);
var file = foldersavearchive.createFile(pdfarchive);
}
/*
fmcmd=12
size=legal/A4
fzr=true/false
portrait=false/true
fitw=true/false
gid=0/1/2
gridlines=false/true
printtitle=false/true
sheetnames=false/true
pagenum=UNDEFINED
attachment=false/true
*/
My problem is the point "Create PDF + update current file. The code is saving a new file with the same name, but than I have of course a new static share link of the menu.
I think I have to use something with the "getblob" function to update the current file.
Would be very good, if anybody would have an idea.
Many thanks.
I was able to find a working solution with Drive.Files.update
// Create PDF + update current file
var fetch='https://docs.google.com/spreadsheets/d/'+fileid+'/export?format=pdf&size=A4&portrait=true&gridlines=false'
var pdf = UrlFetchApp.fetch(fetch, request);
pdf = pdf.getBlob().getAs('application/pdf').setName(name);
var deleteexisting = foldersave.getFilesByName(name);
if (deleteexisting.hasNext() === false) {
// if no file is found then create it
foldersave.createFile(pdf);
} else {
while (deleteexisting.hasNext()) {
var updatedPDF = deleteexisting.next();
Drive.Files.update({mimeType: 'application/pdf'}, updatedPDF.getId(), pdf);
}
}

How to write google script to automatically call data from a google folder drive that contains a CSV file into one Google Sheets

I am trying to write a google script that will allow me to go into my google drive folder called "MeadJohsnon" and pull 'Temperature Calibration.csv' to google sheets. I have never used google script before. Currently I have the "Save Email and Attachment" Add-ons. This add-on is pulling .cvs files that my team is sending me from the field. They use "TapForms" and then send the form via email to my gmail. So, I got the email sending that attachment to my google drive but I need help with the script, so Drive will automatically get those .cvs files and put the information into one google sheet. I say ONE google sheet because although I have a team sending in forms, all the forms have the same information on them.
This is what I have done so far. The fourth line gives me a
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
I would just like feedback on how to fix my error or what I could do instead. As stated this is my first time using google script, my specialty is ASP.net lol not script. Thank you.
function loadingCSV() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sht=ss.getActiveSheet();
sht.clearContents();
var data = loadFile();
var dataA =Utilities.parseCsv(data);
var rng = sht.getRange(1, 1, dataA.length, dataA[0].length);
rng.setValues(dataA);
}
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : 'Temperature Calibration.csv';
var folderID = (typeof(folderID) !== 'undefined')? folderID : '0B8m9xkDP_TJxUUlueHhXOWJMbjg';
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
Okay this will append the files to the active spreadsheet you'll probably have to open the spreadsheet by id and use getSheetByName to get the sheet you want because this spreadsheet probably won't be active all the time when the trigger is running. I assume the the files all end in .csv. I rename them to .old after reading the data so that the program won't read them multiple times.
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;
}