Mail attachment sent by SAP to Google Sheets - excel

Briefly, from an attachment, I am looking to retrieve the data and import it into a Google Sheets spreadsheet.
Context:
An email is sent from SAP once an hour containing an attachment. This attachment can be in ".TXT" format but also in ".XLS" format but the data remains the same (no encoding parameter is available)
A script retrieves the content of the attachment.
If the attachment is in TXT format, then the data is imported into a Google Sheets.
If the attachment is in XLS format, then the attachment is converted and the data is imported into a Google Sheets.
The email containing the attachment is deleted.
Problem:
If the attachment is in TXT format and I display the data as a string,
I get this in the console:
After convert in Spreadsheet :
But for XLS format and I display the data as a string
I get this in the console:
I presume that we can observe those "?" chars due to encoding issues ?
After convert in Spreadsheet :
Why some columns appeared and how to fix it ?
Note:
If I download the XLS file on my computer and then send it back by email and convert it, I don't get the same result as if I converted it directly from the email box. Why is this?
After Convert In Spreadsheet
My scripts :
function main(){
var mailXLS;
var mailTXT;
var mailXLSDownloaded;
var attachmentXLS;
var attachmentTXT
var attachmentXLSDownloaded;
var dataXLS;
var dataTXT;
var dataXLSDownloaded;
mailXLS = GmailApp.getMessageById( "182b5d38f39bf636" ); // XLS mail.
mailTXT = GmailApp.getMessageById( "182b63be8c849b97" ); // TXT mail.
mailXLSDownloaded = GmailApp.getMessageById( "182b6510aa9153d6" ); // XLS Downloaded mail.
attachmentXLS = mailXLS.getAttachments()[0]; // Retrieve the attachment. (XLS file)
attachmentTXT = mailTXT.getAttachments()[0]; // Retrieve the attachment. (TXT file)
attachmentXLSDownloaded = mailXLSDownloaded.getAttachments()[0]; // Retrieve the attachment. (XLS Downloaded file)
dataXLS = attachmentXLS.getDataAsString(); // Data from XLS file.
dataTXT = attachmentTXT.getDataAsString(); // Data from TXT file.
dataXLSDownloaded = attachmentXLSDownloaded.getDataAsString(); // Data from XLS Downloaded file.
Logger.log( dataXLS );
Logger.log( dataTXT );
Logger.log( dataXLSDownloaded );
}
IF attachment is TXT:
// IF attachment is TXT :
var delimiter;
var body;
var spreadsheet;
delimiter = "|";
body = Utilities.parseCsv( dataTXT, delimiter ); // 2-D Array.
spreadsheet = SpreadsheetApp.create(); // new Spreadsheet.
spreadsheet.getSheets()[0].getRange( 1, 1, body.length, body[0].length ).setValues( body ); // Retrieve data.
IF attachment is XLS:
// IF attachment is XLS :
var params;
params = {
"title" : name,
"parents" : [{ "id" : "1234"}]
};
Drive.Files.insert( params, attachment, { "convert" : true} );
Looking for someone to help me in order to get the same Data format for TXT & XLS
Thanks in advance for reading !

dataXLS = attachmentXLS.getDataAsString("UTF-16"); // Data from XLS file.
var body = Utilities.parseCsv(dataXLS,"\t");
var spreadsheet = SpreadsheetApp.create("test"); // new Spreadsheet.
spreadsheet.getSheets()[0].getRange( 1, 1, body.length, body[0].length ).setValues( body ); // Retrieve data.
The issue was the encoding of the XLS file, Apps Script needed accurate encoding format in the instruction blob.getDataAsString() default is UTF-8 and it must be UTF-16.
You just need to add "UTF-16" like blob.getDataAsString("UTF-16")

Related

Attach excel workbook or convert sheets into excel, then send via gmail using gscript, so that workbook is editable by recipient?

I want to be able to send an email to 100+ emails that I have, with an attachment. The attachment needs to be an editable excel file for the recipients. I can access it either as excel or sheets, whichever is easier.
I've tried as much as I could find already online. And I can send a PDF, and I can send a Google Drive link which delivers an editable sheets doc; but I want the end user to be able to access/edit it even if they do not have Google Drive.
This one successfully sends an editable PDF:
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:B2
var dataRange = sheet.getRange(startRow, 1, numRows, 1);
// 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 subject = 'Sending emails from a Spreadsheet'
var file = DriveApp.getFileById("xxxxxxxxx");
MailApp.sendEmail(emailAddress, subject, message, {attachments: [file]});
}
}
I tried this one, to be able to attach a document (hoping an editable excel file) but I get an error code saying that the document is missing (even though it's the exact same doc ID I use in the above, which works):
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:B2
var dataRange = sheet.getRange(startRow, 1, numRows, 1);
// 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 subject = 'Sending emails from a Spreadsheet'
var file = DocumentApp.openById("xxxxxxxxx");
MailApp.sendEmail(emailAddress, subject, message, {attachments: [file]});
}
}
I wanted it to send an excel file, but it won't even find the document even when I use the same doc ID that I use in the 1st syntax above, which works.
This sends an excel doc.. but recipient unable to open. Is this not formatting correctly?
function getGoogleSpreadsheetAsExcel(){
try {
/*var ss = SpreadsheetApp.getActive();*/
var ss = DriveApp.getFileById("xxxxx");
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?
key=" + ss + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("xxxx", "Google Sheet to Excel", "The
XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
Here's the correct syntax to send email from gmail with an excel attachment using google script
function excelemail(){
var file = DriveApp.getFileById('1pJpDI2HD28_gPWGnj-emV0L4rXBBS0HC');
GmailApp.sendEmail('xxxx', 'Attachment example', 'Please see the attached file.' , {attachments: [file], name: 'Automatic Emailer Script' })
}

Updating a google spreadsheet table with an excel file

I need to update a table that is shared. The info for this table is first collected into an Excel table files and then uploaded to google drive every day. I found some code that converts the .xls files to a google spreadsheet file, I need to copy the data from this converted file and update the shared one each day. My problem now is that the file I will use for updating the shared spreadsheet will be different eachday, so how can I have the script to get the new file ID eachday. I need these updates to be done automatically each day.
This is the code I have found so far but can't seem to get it to work. First part converts the .xls file to google spreadsheet file that part works but i cant seem to get the function for updating the shared table to work, i cant get the ID of the created file. Would also be nice if a function an be added to the code to to delete the files after they have been converted and the shared table has been updated with them.
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');
var destinationFolderId = "ID of folder with .xls file that is being converted each day";
var existingFileNames = getFilesInFolder(destinationFolderId);
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
try {
if (existingFileNames[name] && (name.indexOf('.xls')>-1)) {
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name,
key : ID,
'parents':[{"id": destinationFolderId}]
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
} catch (error) {
console.error("Error with file " + name + ": " + error);
}
}
}
/**
* Get an object of all file names in the specified folder.
* #param {string} folderId
* #returns {Object} files - {filename: true}
*/
function getFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var filesIterator = folder.getFiles();
var files = {};
while (filesIterator.hasNext()) {
var file = filesIterator.next();
files[file.getName()] = true;
}
return files;
}
function CopyContent() {
var ID = importXLS(ID);
var source = SpreadsheetApp.openById(importXLS(ID));//the source needs to be the new file i get eachday
var sheet = source.getSheets()[0];
var destination = SpreadsheetApp.openById("ID of shared table here");
sheet.copyTo(destination);
}
Use Paste Special > Paste values only
The copypastetype to use is PASTE_VALUES
Example from https://developers.google.com/apps-script/reference/spreadsheet/range#copytodestination-copypastetype-transposed
// The code below copies only the values of the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("A:E").copyTo(sheet.getRange("F1"), spreadsheetApp.CopyPasteType.PASTE_VALUES);

Dygraphs, comma as decimal separator

I need to plot CSV file with dygraphs but my CSV files use comma as decimal separator.
Format is:
12,46;35,26;5,19
How can I change decimal separator from . to , in dygraphs?
Input file is given like this.
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"values.csv", // path to CSV file
{} // options
);
In order to translate the file content, a possible way is to :
get the file using XMLHttpRequest (like Dygraph does)
tranform the content replacing "," with "."
Next the modified CSV could be given to Dygraph.
This could be achieve with :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
// got the file
var data = xmlhttp.responseText;
// modify content
var data = data.replace(/,/g, ".").replace(/;/g, "\n");
// create the graph with modified data
new Dygraph(document.getElementById("graphdiv2"),data);
}
};
xmlhttp.open("GET","values.csv",true);
xmlhttp.send();

Lotus Notes: Displaying Image attachment on a document

I have a field (Rich Text), that holds the value of an image attachment, but it only display the image path and filename, not as an image display. Am I using the wrong field or there's a problem in my line of code to attach the image? The code to attach is right below:
chqRSIDoc.photodoc = workspace.Openfiledialog(True, "Select a file to attach as photo: ", "", "c:\")
Appreciate all the help.
Thanks!
The openFileDialog returns just a string array. see http://www.ibm.com/support/knowledgecenter/SSVRGU_9.0.0/com.ibm.designer.domino.main.doc/H_OPENFILEDIALOG_METHOD_5310_ABOUT.html
I assume thatyour chqRSIDoc is of NotesDocument. If you want it as an attachment you'll have to use the NotesRichTextItem.EmbedObject function.
Here's an example in Java
Stream stream = this.session.createStream();
MIMEEntity body = doc.createMIMEEntity("dummy");
MIMEHeader header = body.createHeader("Content-type");
header.setHeaderVal("multipart/mixed");
MIMEEntity child = body.createChildEntity();
if (stream.open(filePath))
{
child.setContentFromBytes(stream, "image/jpeg", 1730);
stream.close();
doc.save(true, false);
if (doc.hasItem("Body"))
{
doc.removeItem("Body");
}
RichTextItem rt1 = doc.createRichTextItem("Body");
RichTextItem rt2 = (RichTextItem) doc.getFirstItem("dummy");
rt1.appendRTItem(rt2);
rt2.remove();
doc.save(true, false);
recycle(rt2, rt1, child, header, body);
}

Cakephp .xls file attachment through email component

I am working with CakePHP and need to send mail with .xls file attachment.
Although I have tried a lot but didn't get success.
Note - FYI, Only PDF files are getting attached with the mails.
Please find my code below -
$this->Email->to = 'email address';
$this->Email->from = 'From email address';
$this->Email->subject = 'Subject';
$this->Email->template = 'template name';
$Path = TMP;
$fileName = 'testfile.xls';
$this->Email->filePaths = array($Path);
$this->Email->attachments = array($fileName);
$this->Email->send();
Every time when I execute this code snippet, even mails are receiving but with no attachment.
The documentation ( http://book.cakephp.org/2.0/en/core-utility-libraries/email.html#sending-attachments ) is pretty clear on that.
You need to submit it as an array with the filename as key and the path as array key "file":
$email->attachments(array(
'photo.png' => array(
'file' => '/full/some_hash.png',
'mimetype' => 'image/png',
)
));
I dont know where you got your "filePaths" attribute.

Resources