[英]Import data through Excel sheet in Google sheet with Google Script
I'm trying to get data from a csv file in attachment in my my Gmail, parse it and import it with Google Script in Google Sheets. 我正在尝试从Gmail附件中的csv文件中获取数据,进行解析并将其与Google表格中的Google脚本一起导入。
Problem is when I get content type of my attachment I have this message "application/octet-stream" and not CSV so I think algorithm doesn't keep on in if condition. 问题是,当我获取附件的内容类型时,我收到此消息“ application / octet-stream”,而不是CSV,因此我认为算法不能在if条件下继续运行。
Do you have suggestion why I don't get right file type ? 您有什么建议,为什么我没有正确的文件类型?
Big thanks ! 太谢谢了 !
Here's the code : 这是代码:
function importCSVFromGmail() {
var threads = GmailApp.search("Money Transfer Tracking - Tickets");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
console.log(attachment.getContentType())
// 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);
}
}
If you want to use if (attachment.getContentType() === "text/csv") {}
, it is required to set the mimeType of text/csv
. 如果要使用if (attachment.getContentType() === "text/csv") {}
,则需要设置text/csv
的mimeType。 Also if there is the possibility that attachment
has various mimeTypes, how about this modification? 另外,如果attachment
可能具有各种mimeType,那么该修改如何?
If the attachment file has the filename including the extension, how about this modification? 如果附件文件的文件名包括扩展名,该修改如何? I think that this is more suitable way for your situation, because the attachment files of email often have the filename and the extension. 我认为这是更适合您情况的方法,因为电子邮件的附件文件通常具有文件名和扩展名。
var attachment = message.getAttachments()[0];
attachment.setContentTypeFromExtension(); // Added
If the attachment file has the filename without including the extension, how about this modification? 如果附件文件的文件名不包含扩展名,那么此修改如何?
var attachment = message.getAttachments()[0];
attachment.setContentType("text/csv"); // Added
If this was not the result you want, I apologize. 如果这不是您想要的结果,我深表歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.