[英]Import CSV attachment into google sheets
What I am trying to do, is get the contents of the CSV attachment to output onto Google Sheets. 我想要做的是获取CSV附件的内容以输出到Google表格。 No idea if I am doing this correctly, but I found this online, ran it, and then nothing happens. 我不知道我是否正确地做了这个,但我在网上找到了它,运行它,然后没有任何反应。
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);
}
}
In my environment, I confirmed that when the attached *.csv
file is retrieved from the email, the mimeType is retrieved as application/vnd.ms-excel
. 在我的环境中,我确认当从电子邮件中检索附加的*.csv
文件时,mimeType将作为application/vnd.ms-excel
检索。 I think that the reason of "nothing happens" is this. 我认为“没有发生”的原因就是这个。 So how about these modifications? 那么这些修改怎么样? I think that there are several workarounds for your situation. 我认为您的情况有几种解决方法。 So please think of these modification as 3 of them. 所以请将这些修改视为其中的3个。
application/vnd.ms-excel
模式2:使用mimeType作为application/vnd.ms-excel
Please add the following script before if (attachment.getContentType() === "text/csv") {
. 请在if (attachment.getContentType() === "text/csv") {
之前添加以下脚本if (attachment.getContentType() === "text/csv") {
。
attachment.setContentTypeFromExtension();
Please modify as follows. 请修改如下。
From: 从: if (attachment.getContentType() === "text/csv") {
To:
至:
var fileName = attachment.getName().toUpperCase().split(".");
if (fileName.length > 1 && fileName[1] == "CSV") {
Please modify as follows. 请修改如下。
From: 从: if (attachment.getContentType() === "text/csv") {
To:
至:
var fileName = attachment.getName().toUpperCase().split("."); if (fileName.length > 1 && fileName[1] == "CSV") {
setContentTypeFromExtension()
. 关于模式1,使用setContentTypeFromExtension()
从文件名的扩展名设置mimeType。 application/vnd.ms-excel
. 关于模式2,如果在您的环境中,CSV文件被检索为其他mimeType,请修改application/vnd.ms-excel
。 If these were not what you want, I'm sorry. 如果这些不是你想要的,我很抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.