Insert table from gmail to google spreadsheet by google script

两盒软妹~` 提交于 2020-04-17 05:55:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37072161/insert-table-from-gmail-to-google-spreadsheet-by-google-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!