change output file encoding in a google-script with DriveApp.createFile? - encoding

Let's explain the context of my request : I'm trying to output the content of a google spreadsheet in a .txt tabulated file, encoded in UTF-16, because I need this charset in a later task with this .txt file.
Actually, I've got the right output in the right folder and with the name I want ect ... but the charset is UTF-8 (i've check with an basic text editor).
The problem is I can't find any documentation about charset manipulation with google script. My only solution for now, is a basic manual charset manipulation in sublim text ...
Here's my code (translated from french).
Thank's for your replies !
Maxime
function export() {
//sheet manipulation part
//Get the sheet and set data range i need
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
var values = sheet.getRange(2, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
var text = values.map(function (a) {return a.join('\t');}).join('\n');
//Path setting and export part
// Get sheet info, define path and create file
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var idString = id.toString();
var thisFile = DriveApp.getFileById(idString);
var parentFold = thisFile.getParents();
var folder = parentFold.next();
var theId = folder.getId();
var targetFolder = DriveApp.getFolderById(theId);
targetFolder.createFile('liste du ' + new Date() + '.txt', text, MimeType.PLAIN_TEXT);
}

This helped me:
var string = 'your text here';
var blob = Utilities.newBlob('').setDataFromString(string, "UTF-16");
blob.setName('your_file_name.txt');
var file = DriveApp.createFile(blob);
As a result createFile method will use UTF-16.

This has already been answered in this SO post:
Utilities.newBlob("").setDataFromString("foo", "UTF-8").getDataAsString("UTF-16")

Related

Google Apps Script_populate multiple templates depending on google form data and then email pdf copies

Help greatly needed.
Using Google Form to gather data, in order to populate one of 2 Google doc templates, dependent on whether option 1 or 2 is chosen in the Google form. Populated template to be saved in "final" folder as a PDF, and then emailed to the email address submitted in the Google form.
Currently, I'm able to generate the correct PDF files in the correct folder and send the email to the correct address, but there is no attachment and just the words [Object object].
Before I included the if/else function, I was able to correctly send the email with attachment, which means that I've caused a problem with the if/else and naming of the generated pdfs. I just can't figure it out.
function autoFillGoogleDocFromForm(e) {
//form values
var timestamp = e.values[0];
var firstName = e.values[1];
var lastName = e.values[2];
var email = e.values[3];
var multiplechoice = e.values[4];
if (multiplechoice == "Template 1") {
//This section will complete template 1
var file = DriveApp.getFileById("Template 1 ID");
//Create copy of Template 1
var folder = DriveApp.getFolderById("Templates folder ID")
var copy = file.makeCopy(lastName + ',' + firstName, folder);
//Open copy of Template 1 and replace key fields per form data
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{First Name}}', firstName);
body.replaceText('{{Last Name}}', lastName);
doc.saveAndClose();
Utilities.sleep(1500);
} else {
//This section will complete Template 2 by default
var file = DriveApp.getFileById("Template 2 ID");
//Create copy of Template 2
var folder = DriveApp.getFolderById("Templates folder ID")
var copy = file.makeCopy(lastName + ',' + firstName, folder);
//Open copy of Template 2 and replace key fields per form data
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{First Name}}', firstName);
body.replaceText('{{Last Name}}', lastName);
doc.saveAndClose();
Utilities.sleep(1500);
}
//create pdf copy of completed template either 1 or 2 depending on IF
var pdffolder = DriveApp.getFolderById("Templates folder ID");
var pdfFILE = DriveApp.getFileById(copy.getId()).getAs('application/pdf');
pdfFILE.setName(copy.getName() + ".pdf");
var theFolder = pdffolder;
var theFile = DriveApp.createFile(pdfFILE);
theFolder.addFile(theFile);
Utilities.sleep(1500);
var subject = "File attached";
var attach = theFile;
var pdfattach = attach.getAs(MimeType.PDF);
MailApp.sendEmail(email, subject, {attachments: [pdfattach]});
}
There are two signatures of MailApp that support attachments:
sendEmail(message)
and
sendEmail(recipient, subject, body, options)
There isn't a sendEmail(recipient, subject, options) method signature.
Include a body argument:
MailApp.sendEmail(email, subject, "☢☣☢",{attachments: [pdfattach]});

onFormSubmit(e) I need to sum 4 columns and output to a PDF

This seems like a simple problem, add 4 Form Event columns(Cost 1, Cost 2, Cost 3, Cost 4) and output calculated 'Total' to a PDF via email utilizing a template. I have no problem getting the Event(e) data to the template and sent via email but cannot get the total. I've tried many different Google App Scripts from this site to no avail. Currently, I have a separate sheet called 'Total' and created an array that captures the Event data columns and displays exactly what I want but I cannot get it to the template, problem code may be on line 20. I've included links to the template as well as the Spreadsheet and the Google App Script
// Get template from Google Docs and name it
var docTemplate = "1Ti1n71wpA-U5X9yLqSIfLC9VXqcxOGGsZQhYq0ZwJX4"; // *** replace with your template ID ***
var docName = "Calculate the total";
// When Form Gets submitted
function onFormSubmit(e) {
var name = "Rick"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Total'); //Get 'Total' sheet
var row = sheet.getLastRow(); //Get 'Total' last row
//Get information from form and set as variables
var todaysDate = Utilities.formatDate(new Date(), "CST", "MM/dd/yyyy, hh:mm");
var email_address = "MyEmail address";
var cost1 = e.values[1];
var cost2 = e.values[2];
var cost3 = e.values[3];
var cost4 = e.values[4];
var total = sheet.getRange(row, [1]).getValue(); //Is this the problem?
// Logger.log(e.namedValues);
// Get document template, copy it as a new temp doc, and save the Documents ID
var copyId = DriveApp.getFileById (docTemplate)
.makeCopy(docName + ' for '+ name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the documents body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('<<name>>', name);
copyBody.replaceText('<<cost1>>', cost1);
copyBody.replaceText('<<cost2>>', cost2);
copyBody.replaceText('<<cost3>>', cost3);
copyBody.replaceText('<<cost4>>', cost4);
copyBody.replaceText('<<total>>', total);
copyBody.replaceText('<<timeStamp>>', todaysDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Your Total Cost Project Script";
var body = name + ", here is the total cost for your project ";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
Spreadsheet - https://docs.google.com/spreadsheets/d/144t33X98eZIAH2k5hCA--fFeUzmJCGefKI7lC1EE4Xc/edit?usp=sharing
Template - https://docs.google.com/document/d/1Ti1n71wpA-U5X9yLqSIfLC9VXqcxOGGsZQhYq0ZwJX4/edit?usp=sharing

Script is clearing data too early, does anyone know why?

So I'm working on a project in Google Sheets, using scripting, that will eventually do the following;
Firstly, based on a name in a Cell , find the last 9 entries for that person in form responses.
It then arranges that data in a way that I need and writes it to a sheet, within my spreadsheet
The last part of the script (not my own work, but something i found here)
Script I found online
I've tried to adapt for my needs, not quite there yet. Creates a PDF, saves it in google drive then emails it.
This part requires a bit more work, as I want to specify what the PDF is called using the name and date. Also I'd like to specify where it's saved in google. Lastly the script only produces one PDF. Would like to eventually duplicate the script so I can either create 1 PDF or create them in batches. Will possibly post about these later, if I get stuck.
So anyways that is the overview.
Currently the script works and can query the data I want, write it to a sheet, save it to drive as PDF and email it to a single hard-coded email address. Awesomeness.
But I then tried to add a function called clearRanges which would clear out the template sheet before writing data. I used name ranges to define the 3 sections to clear. But since introducing it, and i've tried it in various parts of my script. I'm getting blank PDF's in my drive and by email.
It's like it's not waiting for the PDF to be created or email to be sent before clearing data. I've tried to put it at the start of my script too, but same thing. Got no idea why.
I was playing around with lock and waitlock as a possible solution, but it didn't seem to help.
If anyone can help out, I'd appreciate it.
function getAgentName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
Browser.msgBox("Please go to the sheet called PDF Creator, in cell A2, choose the agent you wish to create a PDF for");
var sheet = ss.getSheetByName("PDF Creator");
var range = sheet.getRange("A2")
var value = range.getValue();
if (value == 0) {
Browser.msgBox("You need to go to the sheet named PDF Creator and put an agent name in cell A2");
} else {
getAgentData(value);
}
}
function getAgentData(value) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName("Form responses 1")
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var agentData = [];
var commentsData = [];
for (i = 0; i < sourceValues.length; i++) {
// Defines the data layout for PDF.
var agentName = sourceValues[i][2];
var dateTime = sourceValues[i][3];
var callType = sourceValues[i][7];
var opening = sourceValues[i][8];
var rootCause = sourceValues[i][9];
var rootFix = sourceValues[i][10];
var process = sourceValues[i][11];
var consumer = sourceValues[i][12];
var control = sourceValues[i][13];
var wrapup = sourceValues[i][14];
var dpa = sourceValues[i][15];
var score = sourceValues[i][22];
var comments = sourceValues[i][16];
var agentRow = [dateTime, callType, opening, rootCause, rootFix, process, consumer, control, wrapup, dpa, score];
var commentsRow = [dateTime, comments];
if (agentName == value && agentData.length < 9) {
agentData.push(agentRow)
commentsData.push(commentsRow)
}
}
agentData.sort(function (a, b) {
return b[0] - a[0]
});
commentsData.sort(function (a, b) {
return b[0] - a[0]
});
var destSheet = ss.getSheetByName("AgentPDF");
destSheet.getRange("A1").setValue(value + "'s Quality Score card");
var range = destSheet.getRange(6, 1, agentData.length, agentData[0].length);
range.setValues(agentData);
var commentRange = destSheet.getRange(18, 1, commentsData.length, commentsData[0].length);
commentRange.setValues(commentsData);
emailSpreadsheetAsPDF();
}
/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "firstname.lastname#domain.co.uk";
// Subject of email message
// The date time string can be formatted in your timezone using Utilities.formatDate method
var subject = "PDF Reports - " + (new Date()).toString();
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Email Body can be HTML too with your logo image - see ctrlq.org/html-mail
var body = "PDF generated using code at ctrlq.org from sheet " + ss.getName();
var url = ss.getUrl();
url = url.replace(/edit$/, '');
/* Specify PDF export parameters
// From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
exportFormat = pdf / csv / xls / xlsx
gridlines = true / false
printtitle = true (1) / false (0)
size = legal / letter/ A4
fzr (repeat frozen rows) = true / false
portrait = true (1) / false (0)
fitw (fit to page width) = true (1) / false (0)
add gid if to export a particular sheet - 0, 1, 2,..
*/
var url_ext = 'export?exportFormat=pdf&format=pdf' // export as pdf
+ '&size=a4' // paper size
+ '&portrait=1' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid=928916939'; // the sheet's Id
var token = ScriptApp.getOAuthToken();
// var sheets = ss.getSheets();
//make an empty array to hold your fetched blobs
var blobs = [];
// for (var i=0; i<sheets.length; i++) {
// Convert individual worksheets to PDF
// var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob and store in our array
blobs[0] = response.getBlob().setName("Tester " + '.pdf');
// }
//create new blob that is a zip file containing our blob array
// var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');
var test = DriveApp.createFile(blobs[0]);
//optional: save the file to the root folder of Google Drive
DriveApp.createFile(test);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
var lock = LockService.getScriptLock();
GmailApp.sendEmail(email, subject, body, {
attachments: [test]
});
lock.waitLock(20000);
lock.releaseLock();
clearRanges();
}
function clearRanges() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getRangeByName('Header').clearContent();
ss.getRangeByName('Scores').clearContent();
ss.getRangeByName('Comments').clearContent();
}
Can you try adding SpreadsheetApp.flush();
around line 60 before calling emailSpreadsheetAsPDF();
SpreadsheetApp.flush()
commentRange.setValues(commentsData);
SpreadsheetApp.flush();
emailSpreadsheetAsPDF();
I've faced a similar problem before and this worked.

Script to name form response spreadsheet based on form title in Google Drive

I need a script to be able to create the form response spreadsheet of a Google Form and name that Spreadsheet the same as the Form + (Responses) at the end of the name. I have no idea how to do this. I am guessing it has to do with the script below, but the script does not understand that "Title" is the same as a "Name". (I do not know how to append the "(Responses)" part at the end either.) Any help would be appreciated.
function myFunction() {
var form = FormApp.openById('FORM ID HERE').getTitle();
var ss = SpreadsheetApp.create(form);
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
}
I found the answer and also how to apply it to many forms in a folder. The answer is below.
function myFunction() {
var files = DriveApp.getFolderById("0B6Eeub3cEBoobnpxWXdjSWxJRm8").getFiles()
while (files.hasNext()) {
var file = files.next();
var form = FormApp.openById(file.getId());
var formName = DriveApp.getFileById(file.getId()).getName();
var ss = SpreadsheetApp.create(formName + ' (Responses)');
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
}
}

Google Apps Script: read text from a .txt file

After taking a look at the provided tutorial for sending emails from a spreadsheet with Google Apps Script, I modified the given code with aims to be able to send the set of emails out with attachments as well.
It works well enough, even with a couple quirks from the limitations of Google Apps Script (the files have to be in the Google Drive, and all files in the Google Drive with whichever name is appropriate are taken from all folders in the drive).
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var attachment = row[2]; // File name provided.
var subject = "Mass Email";
var files = DriveApp.getFilesByName(attachment); // Get all files with name.
var blobs = []; // Array for attachment.
// Move files into blobs
while (files.hasNext()) {
var file = files.next();
blobs.push(file.getAs(MimeType.PLAIN_TEXT));
}
MailApp.sendEmail(emailAddress, subject, message, {
attachments: blobs, // add attachments
cc: "extra#email.com" // CC to employer
});
}
}
After I first used it, however, I learned that I need to send the files not as attachments, but as the message body of the emails, among some other changes (this is for work). That is, I will only ever email one 'attachment' at a time to each email, and instead of that file being an attachment, its content should be copied over to the message of the email. The attachments are currently text files, and I'd like them to stay that way, but it isn't the most vital thing.
I cannot determine a way to do this with Google Apps Script. Is this possible, or will I have to have a different way of emailing these files? (Hopefully not by hand.)
Try this. It's more faster and simpler.
var docContent = file.getBlob().getDataAsString();
Logger.log(docContent);
as mentioned in my last comment, converting your .txt files to Google documents makes it easy to achieve.
see below (suggestion)
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
Logger.log(row)
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var attachment = row[2]; // File name provided.
var subject = "Mass Email";
var files = DriveApp.getFilesByName(attachment); // Get all files with name.
while (files.hasNext()) {
var file = files.next();
var Id = file.getId();
var content = DocumentApp.openById(Id).getBody().getText();
Logger.log(content)
MailApp.sendEmail(emailAddress, subject, message+'\n'+content)
}
}
}