将日期列附加到从Gmail CSV文件Google Apps脚本导入的数组

cdmah0mi  于 2022-12-25  发布在  Go
关注(0)|答案(1)|浏览(161)

我试图自动导入一份每日报告,这是从第三方系统(我不能编辑发送的值)的电子邮件到谷歌工作表创建一个报告随着时间的推移。
下面的代码可以正常工作并正确导入数据,但是CSV文件不包括日期,这使得无法进行报告。
我可以从电子邮件中获得日期,这也是工作,但我无法将其附加到写入工作表的数据。理想情况下,代码将添加一个额外的条目到数组的每个元素的开始与日期。

/**
 * import CSV data directly from gmail attachments
 */
function importCSVFromGmail() {

  var threads = GmailApp.search('subject:Agent Performance report for newer_than:1d');

  // create empty array to hold data
  var allData = [];

  // get the threads that match this search
  threads.forEach(function(thread) {

    var messageCount = thread.getMessageCount();

    // get the messages in a thread
    var messages = thread.getMessages();

    messages.forEach(function(message) {

      var attachments = message.getAttachments();

      attachments.forEach(function(attachment) {

        // check attachment is CSV
        if (attachment.getContentType() === 'text/csv') {

          // extract the data
          var csvData = Utilities.parseCsv(attachment.getDataAsString());
          var date = Utilities.formatDate(new Date(message.getDate()), "GMT+1", "MM/dd/yyyy");

          allData = allData.concat(csvData);

        }
      });  
      Logger.log(allData);
    }); 
  });

  // paste into Google Sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  sheet.getRange(lastRow + 1, 1, allData.length, allData[0].length).setValues(allData);
}

CSV数据示例

Agent,Tickets assigned,Tickets resolved,Tickets reopened,Tickets reassigned,First response SLA %,Resolution SLA %,FCR %,Private notes,Responses,Average 1st response time,Average response time,Average resolution time
Agent 1,1,2,,1,,100,100,,1,,,17:32:49
Agent 2,11,14,3,,88,86,67,3,15,06:09:35,04:04:20,19:44:18
Agent 3,18,25,7,,100,80,68,6,14,01:28:29,02:35:47,74:48:48

预期输出将只是CSV文件中的数据,日期位于第一列

DD/mm/yyyy,Agent,Tickets assigned,Tickets resolved,Tickets reopened,Tickets reassigned,First response SLA %,Resolution SLA %,FCR %,Private notes,Responses,Average 1st response time,Average response time,Average resolution time
DD/mm/yyyy,Agent 1,1,2,,1,,100,100,,1,,,17:32:49
DD/mm/yyyy,Agent 2,11,14,3,,88,86,67,3,15,06:09:35,04:04:20,19:44:18
DD/mm/yyyy,Agent 3,18,25,7,,100,80,68,6,14,01:28:29,02:35:47,74:48:48
q0qdq0h2

q0qdq0h21#

使用Array.unshiftfor each行:

const csvData = Utilities.parseCsv(attachment.getDataAsString());
const date = Utilities.formatDate(message.getDate(), "GMT+1", "MM/dd/yyyy");
csvData.forEach(row => row.unshift(date));

相关问题