通过谷歌脚本将表格从gmail插入谷歌电子表格

时间:2016-05-06 12:13:23

标签: google-apps-script google-sheets

我在一天内多次收到一张带有桌子的电子邮件,它可能是10x2或40x2或类似的东西。每次我需要将这个表粘贴到工作表中从单元格A1开始/现在我有这个代码,但它将整个表粘贴到单元格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);
    };

请帮我粘贴正确尺寸的桌子。

1 个答案:

答案 0 :(得分:2)

试试这个。

  1. 替换getEmails_(q)功能
  2. <强>代码#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. 替换appendData_功能
    2. <强>代码#2:

       function appendData_(sheet, array2d) {
      
          var h = array2d.length;
          var l = array2d[0].length;
      
          sheet.getRange(1, 1, h, l).setValues(array2d);
       } 
      

      此代码将html文本转换为2d数组,然后将其粘贴到电子表格中。