我一直在使用以下函数将CSV附件加载到谷歌工作表中:
function importCSVFromGmail() {
var threads = GmailApp.search("from:cbuffone123@gmail.com");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var sheet = SpreadsheetApp.getActiveSheet();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
// Remember to clear the content of the sheet before importing new data
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}
函数当前获取从该电子邮件发送的任何附件。我想更改函数,使其只选择名为"data.CSV"的附件,而忽略所有其他附件。有办法做到这一点吗?
提前感谢!
所以我修改为:
function Exact_CSV_Import() {
var threads = GmailApp.search("from:cbuffone123@gmail.com");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
for (var n = 0; n < attachment.length; n++) {
var attachmentName = attachments[n].getName();
if (attachmentName = "data1.csv")
{
// do stuff with "data1.csv"
attachment.setContentTypeFromExtension();
if (attachment.getContentType() === "text/csv") {
var sheet = SpreadsheetApp.getActiveSheet();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}
}
}
似乎什么也没发生。我没有任何错误,但它似乎什么都没做?
此语句:
var attachment = message.getAttachments()[0];
只查看.getAttachments()
返回的附件数组中的第一个附件
而是使用var attachments = message.getAttachments();
然后,您可以循环浏览附件并选择您想要的附件。
此循环将打印出附件的名称及其大小;
for (var n = 0; n < attachments.length; n++) {
Logger.log( attachments[n].getName(), attachments[n].getSize());
}
你应该能够从那里开始。。。
编辑:根据要求选择性处理不同CSV文件的更多说明。。
我很确定attachments
不是一个关联数组,所以你不能做附件["csv"]之类的事情。但是你可以在附件列表中进行迭代,挑选出你想要的名称,然后忽略其余的。。。
for (var n = 0; n < attachments.length; n++) {
var attachmentName = attachments[n].getName();
if (attachmentName = "data1.csv")
{
// do stuff with "data1.csv"
}
else
if ((attachmentName = "data2.csv")
{
// do stuff with "data1.csv"
}
else
{
// do nothing - just skip it
}
}