我一直在使用以下功能将CSV附件加载到Google表格中
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);
}
}
}
}
,似乎什么也没有发生。我没有收到任何错误,但似乎没有任何作用?
答案 0 :(得分:0)
此声明:
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
}
}