I'm using this Google App script
// Reference: https://www.labnol.org/code/20068-blogger-api-with-google-apps-script
function bloggerAPI() {
var api = "https://www.googleapis.com/blogger/v3/users/self/blogs";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(api, options);
var json = JSON.parse(response.getContentText());
for (var i in json.items) {
Logger.log("[%s] %s %s", json.items[i].id, json.items[i].name, json.items[i].url);
}
}
How can I import the values that are in the Logger.log into my sheet.
You have to change the Logger.log() for appendRow().
In your case you have to set the sheet you want to insert the values:
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the Active Spreadsheet
var ss = SpreadsheetApp.openById("ID OF THE SPREADSHEET"); // Alternative way of getting a Spreadsheet
var sheet = ss.getSheets()[0]; // Gets the first sheet
var sheet = ss.getSheets().getSheetByName("Sheet4"); // Gets the sheet with the name Sheet4
Once you have the Spreadsheet you want, inside the for loop, you insert the values:
sheet.appendRow([json.items[i].id, json.items[i].name, json.items[i].url]);
Related
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 })
}
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 !!!
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.
I have a Form that when submitted will trigger a function to write the values of that submittal to the proper sheet in a Spreadsheet.
I then wish to email that adjusted sheet to someone.
I searched google api for help and could not resolve or reverse engineer the proper code
function sendpdf(){ // Function trigger is on form submit
var ss = SpreadsheetApp.getActiveSheet();
var sourceSheet = ss.getSheetName();
var workingRow = ss.getLastRow();
var dataRange = ss.getRange(workingRow, 1, 1, 4);
var data = dataRange.getValues();
var row = data[0]; // entire row
var col1 = row[0]; // first column timestamp A
var col2 = row[1]; // Client B
var col3 = row[2]; // Item C
var sass = SpreadsheetApp.getActiveSpreadsheet();
var targetSheet = sass.getSheetByName(col2);
targetSheet.insertRowBefore(4);
targetSheet.getRange("A4").setValue(col1);
targetSheet.getRange("B4").setValue(col2);
targetSheet.getRange("C4").setValue(col3);
MailApp.sendEmail(to:"reciever#email.com",subject:"See Attached PDF regarding" + col2,body:col2+" submitted a new request"
// , attach:targetSheet.pdf
// need the code to turn the targetSheet into a PDF and then email the PDF
)
}
The Spreadsheet contains 12 sheets and I expect the script to email the proper sheet that was just adjusted to someone any help would be appreciated
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var folderID = "FOLDERID"; // Folder id to save pdf in a folder.
var folder = DriveApp.getFolderById(folderID);
var newSpreadsheet = SpreadsheetApp.create(pdfName); // Name new Spreadsheet
var sheet = sourcesheet.copyTo(newSpreadsheet); //copy activesheet to new spreadsheet
newSpreadsheet.getSheetByName('Sheet1').activate(); //select "sheet1"
newSpreadsheet.deleteActiveSheet(); //delete "sheet1"
var newFile = folder.createFile(newSpreadsheet);
var pdf = DriveApp.getFileById(newSpreadsheet.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(pdfName); //create pdf
from new sheet in folder
var url, //create variable from url of the new sheet
sheets = newSpreadsheet.getSheets()
url = Drive.Files.get(newSpreadsheet.getId())
.exportLinks['application/pdf']; //create the pdf
url = url + '&size=a4' + //paper size
'&portrait=true' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional
'&gridlines=false' + //false = hide gridlines, true = show
'&fzr=false'; //do not repeat row headers (frozen rows) on each page, true = show
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
DriveApp.getFilesByName(pdfName).next().setTrashed(true); //delete newSpreadsheet
var attachmentName = pdfName + '.pdf';
var optAdvancedArgs = {name: "NAMEFROM", htmlBody: htmlBody, replyTo : from,
from:from, attachments: [response.getBlob().setName(attachmentName)], }; //attach pdf
GmailApp.sendEmail(mailTo, subject, body, optAdvancedArgs); //send email with
advanced arguments
This should get you going ...
Good luck !
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]});
}