简体   繁体   中英

Insert table from gmail to google spreadsheet by google script

I recive an email with table many times in one day it can be 10x2 or 40x2 or something like this. Every time I need to paste this table in sheet start from cell A1/ Now I have this code, but it paste whole table to cell A1:

var SEARCH_QUERY = "label:inbox is:unread to:me subject:importnumbers";

// Credit: https://gist.github.com/oshliaer/70e04a67f1f5fd96a708

function getEmails_(q) {
    var emails = [];
    var threads = GmailApp.search(q);
    for (var i in threads) {
        var msgs = threads[i].getMessages();
        for (var j in msgs) {
            emails.push([msgs[j].getBody().replace(/<.*?>/g, '\n')
                .replace(/^\s*\n/gm, '').replace(/^\s*/gm, '').replace(/\s*\n/gm, '\n')
            ]);
        }
    }
    return emails;
}  
  function appendData_(sheet, array2d) {

      sheet.getRange(1, 1).setValues(array2d);
      }

    function saveEmails() {
        var array2d = getEmails_(SEARCH_QUERY);
        if (array2d) {
            appendData_(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('numberlist'), array2d);
        }
      markArchivedAsRead ();
    }

    function markArchivedAsRead() {
      var threads = GmailApp.search('label:inbox is:unread to:me subject:importnumberlist');
      GmailApp.markThreadsRead(threads);
    };

Please, help me to paste table with right dimensions.

Try this one.

  1. Replace getEmails_(q) function

Code#1:

function getEmails_(q) {
    var emails = [];
    var threads = GmailApp.search(q);
    for (var i in threads) {
        var msgs = threads[i].getMessages();
        for (var j in msgs) {

            var arrStr = msgs[j].getBody()
              .replace(/<\/tr>/gm, '[/tr]')
              .replace(/<\/td>/gm, '[/td]')
              .replace(/<.*?>/g, '\n')
              .replace(/^\s*\n/gm, '')
              .replace(/^\s*/gm, '')
              .replace(/\s*\n/gm, '\n')
              .split("[/tr]");

            var line = [];

            for (var i = 0; i < arrStr.length - 1; i++) {

              line = arrStr[i].split("[/td]");
              line.length -= 1;
              emails.push(line);
            }
        }
    }
    return emails;
}
  1. Replace appendData_ function

Code#2:

 function appendData_(sheet, array2d) {

    var h = array2d.length;
    var l = array2d[0].length;

    sheet.getRange(1, 1, h, l).setValues(array2d);
 } 

This code converts the html text into 2d array and then paste it into Spreadsheet.

Note 2020-06

Your email may (1) contain several tables or (2) a table with merged cells. In this case, the proposed script may cause an error:

The number of columns in the data does not match the number of columns in the range

In this situation, you'll need to create another function to parse the message body. I suggest you see the HTML-code of your message and inspect it in Gmail:

Right Click > Instect

or [Ctrl]+[Shift]+[I]

The other approach in this situation is to paste data "as is", use sample function to convert any 2d array into rectangular:

function convert2ArrayToRectangular_(array2d)
{
  // get max width
  var res = [];
  var w = 0;
  for (var i = 0; i < array2d.length; i++)
  {
    if (array2d[i].length > w) {w = array2d[i].length;}    
  }

  var row = [];
  for (var i = 0; i < array2d.length; i++)
  {
    row = array2d[i];
    if(array2d[i].length < w)
    {
      for (var ii = array2d[i].length; ii < w; ii++)
      {
        row.push('');        
      }  
    }
    res.push(row);
  }
  return res;
}

Sample usage:

function test_get_email() {
  var q = 'Test_table_to_sheets';
  var array2d = getEmails_(q);  
  var sheet = SpreadsheetApp.openById('1BKkd5LwBYyGoi2um-S3pTCBKrUEko34m9vJu94K8uOQ').getSheetByName('Test_table_to_sheets2');
  appendData_(sheet, convert2ArrayToRectangular_(array2d));
}

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