简体   繁体   中英

Extract data from gmail & pass to Google sheet

I got code for extracting data from Gmail and pass it to google sheet.

Please find the code.

在此处输入图像描述

The problem for me is, the entire data is being copied to the first row alone.

Gmail message:

UserName    ID
XXX         23
YYY         45

What I got in Google sheet is: entire 3*4 table format content in first row(A1) itself.

I need to append this information in separate cells instead of single cell.

You are not specifying which cells you want it to go in and you therefore keep appending into cell A1 (extremely and terribly inefficient) the code below is specifying cell A1 down.

function addToDo() {

    var label = GmailApp.getUserLabelByName("Samples");
    var threads = label.getThreads();
    var sheet = SpreadsheetApp.getActiveSheet();
    var body = [];

    for(var i=0;i<threads.length; i++){
         body[body.length] = [threads[i].getMessages()[0].getPlainBody()]; //add to array in google app scripts
    }

    sheet.getRange(1,1,body.length,1).setValues(body); //dump array all at once to google sheets
}

Please read this resource as it will help you from making more terrible mistakes in your GAS (google app script) code as relating to google sheets. The first bad example is exactly what you were trying to do.

https://developers.google.com/apps-script/guides/support/best-practices

Your code has the issue where it inserts a single object as a cell and it does it in an inefficient way.

You should get all the data and set it at once. This allows Google to perform bulk operations that are more efficient.

Also, if you want to insert the data in multiple columns, you need to separate it and place each columns as an object (in my example, into data ).

function myFunction() {
  var label = GmailApp.getUserLabels()[0];
  var threads = label.getThreads();
  var sheet = SpreadsheetApp.getActiveSheet();

  var data = [];

  for (var i=0; i<threads.length; i++) {
    var threadId = threads[i].getId();
    var firstmessage = threads[i].getMessages()[0];
    var subject = firstmessage.getSubject();
    var body = firstmessage.getPlainBody();
    data.push([threadId, subject, body]); //Change this to have the columns you want
  }

  sheet.getRange(sheet.getDataRange().getLastRow(), 1, data.length, data[0].length).setValues(data);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM