I am running a simple function to extract a CSV attachment from my Gmail to a Google Sheet. It works perfectly for all my other CSVs except for one.
This is the script I am running:
function getCsvFromGmail() {
// Get the newest Gmail thread based on sender and subject
var gmailThread = GmailApp.search("from:[email protected] subject:\"testfile\"", 0, 1)[0];
// Get the attachments of the latest mail in the thread.
var attachments = gmailThread.getMessages()[gmailThread.getMessageCount() - 1].getAttachments();
// Get and and parse the CSV from the first attachment
var csvData = Utilities.parseCsv(attachments[0].getDataAsString());
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
The error I am receiving:
Exception: Could not parse text.
Here is a link to the sample dataset: https://drive.google.com/file/d/1MNI01XK2HmZ8Nedm9-3U9mjEsls0hoqe/view?usp=sharing
The error could be due to the line break on field19
. Is there a way I can add in an extra line of code to fix this?
Thank you.
CodePudding user response:
Try this. It turns out its not \n
but \r
var attachment = attachments[0].getDataAsString();
attachment = attachment.replace(/\r/g," ");
// Get and parse the CSV from the first attachment
var csvData = Utilities.parseCsv(attachment);