我正在尝试将通过第三方系统(无法编辑所发送的值)通过电子邮件发送的每日报告自动导入到Google工作表中,以便随着时间的推移创建报告。
下面的代码可以正常工作并正确导入数据,但是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
const csvData = Utilities.parseCsv(attachment.getDataAsString());
const date = Utilities.formatDate(new Date(message.getDate()), "GMT+1", "MM/dd/yyyy");
csvData.forEach(row => row.unshift(date));