A file in XLSX format comes to the mail, I want the data from XLSX to be transferred to a Google spreadsheet via Google Drive, I found the code, but it gives an error.
ReferenceError: fileInfo is not defined
function importProduct() {
var requete ="1yflLPUWI2Dqz1P0kXabg-eFA3nhYmujA"
var threads = GmailApp.search(requete);
for (var i = 0; i \< threads.length; i++) {
var messages = threads\[i\].getMessages();
Logger.log(messages)
}
const file = Drive.Files.insert(fileInfo, excelFile, {convert: true})
}
function getExcelFile(thread)
{
var messages = thread.getMessages();
var len = messages.length;
var message = messages\[len-1\]
var attachments = message.getAttachments();
var xlsxBlob = attachments\[0\];
Logger.log(xlsxBlob.getContentType())
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
var filename = xlsxBlob.getName();
var tabName = filename.substring(13).slice(0,filename.length-18);
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()\[0\];
var destination = SpreadsheetApp.openById("1lfDEEn1PpTh5dja6VOPvKvMVPPCBA5xgV6uVRemKmcc");
var sss=destination.getSheetByName("All");
Drive.Files.remove(convertedSpreadsheetId);
labelName='Addop';
deleteForever(labelName);
}
Related
I want to only copy the CSV attachment to google sheets from an email.
The email has multiple attachments, in different file formats.
The attachment I want to copy over is consistently the same name in csv format.
I am using this code but its not pulling the attachment I want to copy to google sheet.
Can someone help me with this.
function getCSV() {
var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
var threads = myLabel.getThreads(0,1);
var msgs = GmailApp.getMessagesForThreads(threads);
var attachments = msgs[0][0].getAttachments();
var csv = attachments[0].getDataAsString();
var data = Utilities.parseCsv(csv);
var a = data.length ;
var b = data[0].length;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
sheet.getRange('A2:AM6026').clearContent();
var range = sheet.getRange(2,1, data.length,data[0].length);
range.setValues(data);
}
Loop over the attachments and get the filename. Quick edit to your existing code:
function getCSV() {
var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
var threads = myLabel.getThreads(0, 1);
var msgs = GmailApp.getMessagesForThreads(threads);
var attachments = msgs[0][0].getAttachments();
attachments.forEach(att => {
const name = att.getName()
if (name == "myFileName.csv") {
var data = Utilities.parseCsv(att.getDataAsString());
var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
sheet.getRange('A2:AM6026').clearContent();
var range = sheet.getRange(2, 1, data.length, data[0].length);
range.setValues(data);
}
})
}
I two spreadsheet Main and AddFiles wherein Add file has Two columns Subject and Attachments where under attachments is the list of excel file names with like file1.xlsx and file2.xlsx. Where I uploaded this file in my Google Drive under the Report folder.
I used the code below but always got an error on the last execution. It doesn't recognize the .getAs(MimeType.xlsx)
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(2,1,1,1)
data = dataRange.getValues()
var e = data[0][0]
for (var i = 0; i < (e-1); i++) {
draftmail();
}
function draftmail(){
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(1,1,1,1)
var data = dataRange.getValues()
var msg = data[0][0]
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("AddFiles");
var startRowx = 1
var numRowx = 1
var dataRangeTox = sheet.getRange(startRowx,3,numRowx,1)
var datax = dataRangeTox.getValues()
for (x in datax) {
var rowx = datax[x];
var to = rowx[0];
var Starta = 2 + i
var numRowa = 1
var dataRangeToa = sheet2.getRange(Starta,1,1,1)
var dataa = dataRangeToa.getValues()
for (a in dataa) {
var rowa = dataa[a];
var subject = rowa[0];
var Startb = 2 + i
var numRowb = 1
var dataRangeTob = sheet2.getRange(Startb,2,1,1)
var datab = dataRangeTob.getValues()
for (b in datab) {
var rowb = datab[b];
var datafile = rowb[0];
var file = DriveApp.getFilesByName(datafile)
var startRowy = 1
var numRowy = 1
var dataRangeToy = sheet.getRange(startRowy,4,numRowy,1)
var datay = dataRangeToy.getValues()
for (y in datay) {
var rowy = datay[y];
var carboncopy = rowy[0];
if (file.hasNext()){
GmailApp.createDraft(to,subject,msg,{ cc: carboncopy}, {
attachments: [file[0].getAs(MimeType.xlsx)],
})
}
}
}
}
}
}
Modification points:
Assuming that everything else works properly in your code, you should make the following changes:
cc and attachments should be passed as a single json object.
file[0] should be file.next().
MimeType.xlsx should be MimeType.MICROSOFT_EXCEL.
Solution:
GmailApp.createDraft(to,subject,msg,
{ cc: carboncopy,
attachments: [file.next().getAs(MimeType.MICROSOFT_EXCEL)]
})
References:
Class GmailApp
Google Apps Script: XLSX from Gmail to Google Sheets: invalid mime type. Content type seems to be application/octet?
Class FileIterator
When you call
file = DriveApp.getFilesByName(datafile)
it returns a FileIterator collection, which is not indexed like an array (file[0]) but rather requires you to call file.next() to get the next file.
In addition, the MimeType Enum for an .xlsx file is MimeType.MICROSOFT_EXCEL.
So change
attachments: [file[0].getAs(MimeType.xlsx)]
to this instead:
attachments: [file.next().getAs(MimeType.MICROSOFT_EXCEL)]
I am trying to copy a table from Google Sheet that includes pictures into a Google doc.
So far I managed to accomplish several things, but not the result that I need.
Source Google Sheet - table with pictures, filled by Importrange formula from another Google sheet.
Copying via appendTable does not copy pictures
I managed to export table to a pdf blob, but couldn't convert it to a regular Google doc then.
Any help appreciated.
function printDocument() {
var source = SpreadsheetApp.getActive();
var spreadsheetId=source.getId();
var sourcesheet = source.getSheetByName('Printable Shooting Plan');
var sheetId = sourcesheet.getSheetId();
var current_lastrow = getLastPopulatedRow(sourcesheet);
var srcData = sourcesheet.getRange('A1:G'+current_lastrow).getValues();
var parents = DriveApp.getFileById(source.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
var doc = DocumentApp.create("Shooting Plan");
var body = doc.getBody();
body.insertParagraph(0, 'Shooting Plan').setHeading(DocumentApp.ParagraphHeading.HEADING1).setAlignment(DocumentApp.HorizontalAlignment.CENTER);
table = body.appendTable(srcData);
table.getRow(0).editAsText().setBold(true);
// Copy doc to the directory we want it to be in. Delete it from root.
var docFile = DriveApp.getFileById(doc.getId());
folder.addFile(docFile);
DriveApp.getRootFolder().removeFile(docFile);
}
function onOpen() {
var submenu = [{name:"Save Doc", functionName:"printDocument"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function getLastPopulatedRow(sheet) {
var data = sheet.getDataRange().getValues();
for (var i = data.length-1; i > 0; i--) {
for (var j = 0; j < data[0].length; j++) {
if (data[i][j]) return i+1;
}
}
return 0;
}
Thank you in advance for helping.
I am trying to convert the most recent submitted data from Google Form/Google sheets to a "template" Google doc. Basically, when a user submit a form, it will convert the data from Google Sheet and create a new Google Doc.
Side note: Im not really a coder.. I found the base script online and tried to modified it accordingly. I would greatly appreciate a step by step if possible?
AGAIN, THANK YOU SO MUCH
function createDocument() {
var headers = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A1:AU1');
var tactics = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A2:AU2');
var templateId = 'DOCTEMPLATE-ID';
for(var i = 0; i < tactics.values.length; i++){
var Fclient = tactics.values[i][0];
var Lclient = tactics.values[i][1];
var birthday = tactics.values[i][2];
var profession = tactics.values[i][3];
var email = tactics.values[i][4];
var phone = tactics.values[i][5];
var whatsapp = tactics.values[i][6];
var preferredcontact = tactics.values[i][7];
var UScitizen = tactics.values[i][8];
var Ocitizen = tactics.values[i][9];
var Tsapre = tactics.values[i][10];
var Pairplane = tactics.values[i][11];
var Photelamen = tactics.values[i][12];
var FFlyer = tactics.values[i][13];
var hotelloy = tactics.values[i][14];
var vistedcountries = tactics.values[i][15];
var smoke = tactics.values[i][16];
var allergies = tactics.values[i][17];
var Othermed = tactics.values[i][18];
var addANOTHER = tactics.values[i][19];
var emergencyname = tactics.values[i][20];
var emergencyphone = tactics.values[i][21];
var emergencyrelation = tactics.values[i][22];
var emergencyname2 = tactics.values[i][23];
var emergencyphone2 = tactics.values[i][24];
var emergencyrelation2 = tactics.values[i][25];
var comptravelmag = tactics.values[i][26];
var secondaryFname = tactics.values[i][27];
var secondaryLname = tactics.values[i][28];
var secondarybirthday = tactics.values[i][29];
var secondaryprofession = tactics.values[i][30];
var secondaryemail = tactics.values[i][31];
var secondaryphone = tactics.values[i][32];
var secondarywhatsapp = tactics.values[i][33];
var secondarypreferredcontact = tactics.values[i][34];
var secondaryUScitizen = tactics.values[i][35];
var secondaryOcitizen = tactics.values[i][36];
var secondaryTsapre = tactics.values[i][37];
var secondaryPairplane = tactics.values[i][38];
var secondaryPhotelamen = tactics.values[i][39];
var secondaryFFlyer = tactics.values[i][40];
var secondaryhotelloy = tactics.values[i][41];
var secondaryvistedcountries = tactics.values[i][42];
var secondarysmoke = tactics.values[i][43];
var secondaryallergies = tactics.values[i][44];
var secondaryOthermed = tactics.values[i][45];
var timestamp = tactics.values[i][46];
//Make a copy of the template file
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName('Basic Information: ' + Lclient + 'test');
//Get the document body as a variable.
var body = DocumentApp.openById(documentId).getBody(); **ERROR HERE**
//Insert the supplier name
body.replaceText('{{Fcilent}}', Fclient);
body.replaceText('{{Lcilent}}', Lclient);
body.replaceText('{{birthday}}', birthday);
body.replaceText('{{profession}}', profession);
body.replaceText('{{email}}', email);
body.replaceText('{{phone}}', phone);
body.replaceText('{{whatsapp}}', whatsapp);
body.replaceText('{{preferredcontact}}', preferredcontact);
body.replaceText('{{UScitizen}}', UScitizen);
body.replaceText('{{Ocitizen}}', Ocitizen);
body.replaceText('{{Tsapre}}', Tsapre);
body.replaceText('{{Pairplane}}', Pairplane);
body.replaceText('{{Photelamen}}', Photelamen);
body.replaceText('{{FFlyer}}', FFlyer);
body.replaceText('{{hotelloy}}', hotelloy);
body.replaceText('{{vistedcountries}}', vistedcountries);
body.replaceText('{{smoke}}', smoke);
body.replaceText('{{allergies}}', allergies);
body.replaceText('{{Othermed}}', Othermed);
body.replaceText('{{addANOTHER}}', addANOTHER);
body.replaceText('{{emergencyname}}', emergencyname);
body.replaceText('{{emergencyphone}}', emergencyphone);
body.replaceText('{{emergencyrelation}}', emergencyrelation);
body.replaceText('{{emergencyname2}}', emergencyname2);
body.replaceText('{{emergencyphone2}}', emergencyphone2);
body.replaceText('{{emergencyrelation2}}', emergencyrelation2);
body.replaceText('{{comptravelmag}}', comptravelmag);
body.replaceText('{{secondaryFname}}', secondaryFname);
body.replaceText('{{secondaryLname}}', secondaryLname);
body.replaceText('{{secondarybirthday}}', secondarybirthday);
body.replaceText('{{secondaryprofession}}', secondaryprofession);
body.replaceText('{{secondaryemail}}', secondaryemail);
body.replaceText('{{secondaryphone}}', secondaryphone);
body.replaceText('{{secondarywhatsapp}}', secondarywhatsapp);
body.replaceText('{{secondarypreferredcontact}}', secondarypreferredcontact);
body.replaceText('{{secondaryUScitizen}}', secondaryUScitizen);
body.replaceText('{{secondaryOcitizen}}', secondaryOcitizen);
body.replaceText('{{secondaryTsapre}}', secondaryTsapre);
body.replaceText('{{secondaryPairplane}}', secondaryPairplane);
body.replaceText('{{secondaryPhotelamen}}', secondaryPhotelamen);
body.replaceText('{{secondaryFFlyer}}', secondaryFFlyer);
body.replaceText('{{secondaryhotelloy}}', secondaryhotelloy);
body.replaceText('{{secondaryvistedcountries}}', secondaryvistedcountries);
body.replaceText('{{secondarysmoke}}', secondarysmoke);
body.replaceText('{{secondaryallergies}}', secondaryallergies);
body.replaceText('{{secondaryOthermed}}', secondaryOthermed);
body.replaceText('{{timestamp}}', timestamp);
//Append tactics
parseTactics(headers.values[0], tactics.values[i], body);
}
}
function parseTactics(headers, tactics, body){
for(var i = 1; i < tactics.length; i++){
{tactics[i] != '' &&
body.appendListItem(headers[i] + ' | ' + tactics[i] + ' OTHER').setGlyphType(DocumentApp.GlyphType.BULLET);
}
}
}
Error: "We're sorry, a server error occurred. Please wait a bit and try again. (line 63, file "Code")"
I expected the script to generate a new google doc from the data sheet as it is being submitted on google form.
I think your pretty close. Here's an example I did.
First, I created a function to generate some data for myself.
function testData() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.clearContents();
var rg=sh.getRange(1,1,10,10);
var vA=rg.getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
vA[i][j]=Utilities.formatString('row: %s - col: %s',i+1,j+1);
}
}
rg.setValues(vA);
}
The above function creates a sheet that looks like this:
The Template File Looks like this:
And after running this code:
function createDoc(){
var spreadsheetId='spreadsheet Id';
var templateId='template Id';
var data=Sheets.Spreadsheets.Values.get(spreadsheetId,'Sheet177!A1:J2');//range include sheet name
var docId=DriveApp.getFileById(templateId).makeCopy('Test').getId();
var body=DocumentApp.openById(docId).getBody();
for(var i=0;i<data.values.length;i++) {
for(var j=0;j<data.values[i].length;j++) {
var s=Utilities.formatString('{{col%s-%s}}',i+1,j+1);
body.replaceText(s,data.values[i][j]);
}
}
}
There appears in the same folder another file named test that looks like this:
I must say that sure is a simple way to get data.
I'm kind of wondering if perhaps you simply didn't authenticate the program in the script editor.
I have two Google Script codes that automate the process of importing email attachments from Gmail (it's automatically labeled) into Google Sheets. So far I managed to make it work for CSV and XLSX files separately. Please see both codes below. My question is: how do I combine those two codes into one, so that it could determine the file extension automatically and apply the right parsing technique when copying the contents of the files in the respective Google Sheet. Thank you!
For XLSX files:
function getXLSX() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
/* var message = thread[0].getMessages()[0]; // Get first message */
var messages = thread[0].getMessages();
var len = messages.length;
var message=messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var xlsxBlob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet_new = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
/*for (var i = 0; i > sheet_new.length; i++) {
var range = sheet_new[i].getRange("A:I");
range.clearContents();
}*/
sheet_new.clearContents();
var range = sheet_new.getRange(1,1, data.length,data[0].length);
range.setValues(data);
}
For CSV files:
function getCSV() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
/* var message = thread[0].getMessages()[0]; // Get first message */
var messages = thread[0].getMessages();
var len = messages.length;
var message=messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var csv = attachments[0].getDataAsString();
var data = Utilities.parseCsv(csv);
var a = data.length ;
var b = data[0].length;
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet.getRange("A:J").clear();
var range_final = sheet.getRange(1,1, data.length,data[0].length);
range_final .setValues(data);
}
How about this modification? In this modification, the mimeType is compared and each script is run. Please think of this as just one of several answers.
Modified script:
function myFunction() {
var thread = GmailApp.getUserLabelByName("Invoicing").getThreads(0,1);
var messages = thread[0].getMessages();
var len = messages.length;
var message = messages[len-1]; //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var blob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
blob.setContentTypeFromExtension();
if (blob.getContentType() == MimeType.MICROSOFT_EXCEL) {
// Process for XLSX
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, blob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
var sheet_new = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet_new.clearContents();
var range = sheet_new.getRange(1,1, data.length,data[0].length);
range.setValues(data);
} else if (blob.getContentType() == MimeType.CSV) {
// Process for CSV
var csv = blob.getDataAsString();
var data = Utilities.parseCsv(csv);
var a = data.length ;
var b = data[0].length;
var sheet = SpreadsheetApp.openById("1jRh8sj_jAaZKH4xbdpI9Q4to1tKuGWTTO2MzHlU").getSheetByName("Data drop");
sheet.getRange("A:J").clear();
var range_final = sheet.getRange(1,1, data.length,data[0].length);
range_final.setValues(data);
}
}
Note:
This modified script supposes as follows.
The index of 0 of attachment files is the file you need.
The index of 0 of attachment files is XLSX file or CSV file.
Filenames of XLSX and CSV files have the extension of .xlsx and .csv, respectively.
Reference:
setContentTypeFromExtension()
If I misunderstood your question and this was not the result you want, I apologize.