Convert Google Sheet to CSV then attach it to an email - google-apps-script

I have a simple Apps Script need, but can't find a near enough sample from the community.
I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email.
So far, I found a script to convert a sheet into a CSV format and file it in a folder.
I looked for a script to add that will instead attach the CSV file to an email, but can't find anything which I can use based on my novice level of Apps Script knowledge.
Any help will be greatly appreciated. Thank you very much.
Script:
function sheet1ToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "xxxx"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var folderId = "yyyy";
var csvContent = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{id: folderId}]
}
var fileJson = Drive.Files.insert(csvContent,result)
}

In your showing script, an email is not sent. And, only one CSV file is created to Google Drive. From I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email. and your showing script, when your showing script is modified, how about the following modification?
Modified script:
function myFunction() {
var emailAddress = "###"; // Please set your email address.
var sheetNames = ["Sheet1", "Sheet2"]; // Please set your 2 sheet names you want to use.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = ss.getId();
var requestData = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var blobs = sheetNames.map(s => {
var params = ssID + "/export?gid=" + ss.getSheetByName(s).getSheetId() + "&format=csv";
var url = "https://docs.google.com/spreadsheets/d/" + params;
return UrlFetchApp.fetch(url, requestData).getBlob().setName(s); // <--- Modified
});
MailApp.sendEmail({ to: emailAddress, subject: "sample subject", body: "sample body", attachments: blobs });
}
When this script is run, an email is sent by including 2 CSV files as the attachment files.
References:
map()
sendEmail(message)

function myfunk() {
const folder = DriveApp.getFolderById("folderid");
const ss = SpreadsheetApp.getActive();
const names = ["Sheet1", "Sheet2"];
const params = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
let bA = [];
names.forEach(n => {
let sh = ss.getSheetByName(n);
let url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?gid=" + sh.getSheetId() + "&format=csv";
let r = UrlFetchApp.fetch(url, params);
let csv = r.getContentText();
let file = folder.createFile(n, csv, MimeType.CSV);
bA.push(file.getBlob());
})
GmailApp.sendEmail(recipient, subject, body, { attachments: bA })
}

Related

Script to automatically send a Sheet by email

I am trying to automate by a script the sending of a Sheet (active or not) of a workbook and only one sheet and not the whole workbook to a list of email addresses. Furthermore, I would like the Sheet to be converted to excel format when it is attached to the email.
Thank you for your answers
Try this:
function emailSpreadsheetAsPDF() {
const sheetToPrint = 'SPREADSHEET_NAME'; // name of the sheet to print
const ss = SpreadsheetApp.getSheetByName('SHEET_NAME'); // the sheets to use
const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME').getRange('RANGE').getValue().toString(); // grab the email address from the specified cell
const subject = `SUBJECT - ${ss.getName()}`; // the subject of the email
const body = "BODY"; // body of the email
const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
const exportOptions =
'exportFormat=pdf&format=xlsx' + // export as pdf / csv / xls / xlsx
'&gid='+shID; // the sheet's Id
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// generate the file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// send the email to the specified address with the specified body text and attached file
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: `EKOL Hungary - ${ss.getName()}` + ".xlsx",
content: response.getBytes(),
mimeType: "application/xlsx"
}]
});
}
Just substitute the SPREADSHEET_NAME, SHEET_NAME, RANGE, and BODY to what is true for your spreadsheet.
You can add a Trigger under the Triggers menu point (left side of the Script Editor) to automatically run the script whenever you want it to run.
Thanks but I failed to use it
But by combining several scripts, I found one that works:
function onSubmit(e){
Logger.log('submit ran');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Send active sheet as email attachment
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "xxx#xx";
var subject = "xxxxx";
var body = "xxxxx";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=false" + "&exportFormat=xlsx";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
};
Now what I would like is to be able to send the sheet to email addresses located on another sheet.
Also in "subject", I would like to combine "xxxx" + a date in a cell of the active sheet: "xxxx dd / mm / yyyy"
I haven't figured out how to do it yet !!!

google app script export csv with semicolon instead of comma

I am using the code below to export a google spreadsheet to CSV in a specific folder.
I need to have a semicolon (;) as delimiter instead of a comma (,)
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var parentFolder = DriveApp.getFolderById("MyID");
var folder = parentFolder;
var curDate = Utilities.formatDate(new Date(), "GMT+1", "yyyyMMdd")
var fileName = "MyName" + curDate + ".csv";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
}
Thank you for your help
You want to replace , to ; for the retrieved CSV data.
You want to create the replaced data as a file.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
The data that ; is used as the delimiter instead of , is no mimeType of text/csv. In this case, it is required to be text/plain.
In your script, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, the values are retrieved and the data separated by ; is created.
Modified script:
When your script is modified please modify as follows.
From:
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
To:
var values = sheet.getDataRange().getValues();
var outputData = values.map(r => r.join(";")).join("\n");
folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
Pattern 2:
In this pattern, the retrieved CSV data is converted.
Modified script:
When your script is modified please modify as follows.
From:
folder.createFile(response.getBlob().setName(fileName));
To:
var csvData = Utilities.parseCsv(response.getBlob().getDataAsString());
var outputData = csvData.map(r => r.join(";")).join("\n");
folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
Note:
Please enable V8.
Reference:
createFile(name, content, mimeType)
If I misunderstood your question and this was not the direction you want, I apologize.

how Send specific part of the sheet as email?

this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.

how to make this template code work from sheets app

I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
var input = e.values[1];
if (input == 'my_password'){
// your scripts to create and send the PDF goes here
}
}
It's a simplistic solution, but it works.

How to mail a specific sheet in a spreadsheet with selected column as .XLSX file?

I have a spreadsheet and I want to use Google App Script to auto send email with attachment is one sheet of the spreadsheet in .XLSX file. I can do it with the showed code below, but I do not know how to send this sheet with like only columns from "A" to "F" for example. I've searched but still can not find a way, so please help me with this. Thank guys
function getSheetID(name){
var ss = SpreadsheetApp.getActive().getSheetByName(name)
var sheetID = ss.getSheetId().toString()
return sheetID
}
function getGoogleSpreadsheetAsExcel(){
var ss = SpreadsheetApp.getActive();
var shID = getSheetID("SHE");
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?format=xlsx&gid="+shID;
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName("SHE.xlsx");
MailApp.sendEmail("test#gmail.com", "Test send only one sheet of whole spreadsheet", "Hi Ted, I", {attachments: [blob]});
}