Get CSV attachment from Gmail and add data to sheet

880 views
Skip to first unread message

sben...@bbchs.org

unread,
Oct 27, 2021, 7:37:28 AM10/27/21
to Google Apps Script Community
Is there a way to get a csv attachment and add that to range in a Google sheet?  
I can do most of this, I am not sure how to get the csv as an array to paste it to a range.

Thanks  

Alan Wells

unread,
Oct 27, 2021, 9:57:36 AM10/27/21
to Google Apps Script Community

Bennett, Scott

unread,
Nov 5, 2021, 7:45:00 AM11/5/21
to google-apps-sc...@googlegroups.com
Don't remember where I found this, but this did end up working for anyone else that might need it.

function getAttachment() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getSheetByName('All Data');
  var lrow = sheet.getLastRow()
  var emails = GmailApp.search('Message Subject',0,1)
  for(i = 0;i<emails.length;i++){
    var messages=emails[i].getMessages()
    for(m=0;m<messages.length;m++){
      var attachment=messages[m].getAttachments()[0]
      var csv = Utilities.parseCsv(attachment.getDataAsString())
      csv.shift()
      Logger.log(csv)
      if(csv.length<800){
        sheet.getRange(lrow+1,1,csv.length,csv[0].length).setValues(csv)
      }
    }
  }
}

The code only searches for the first email with the subject. I intentionally left the emails variable in case I ever want to search for more than 1 message.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/6f1f7d98-784a-48cd-879d-5a45e09be9dan%40googlegroups.com.


--
Scott Bennett


Reply all
Reply to author
Forward
0 new messages