简体   繁体   中英

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. 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 . 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.

Modification points:

  • Pattern 1: Set the mimeType from filename.
  • Pattern 2: Use the mimeType as application/vnd.ms-excel
  • Pattern 3: Use the extension.

Pattern 1:

Please add the following script before if (attachment.getContentType() === "text/csv") { .

attachment.setContentTypeFromExtension();

Pattern 2:

Please modify as follows.

From:
 if (attachment.getContentType() === "text/csv") { 
To:
var fileName = attachment.getName().toUpperCase().split(".");
if (fileName.length > 1 && fileName[1] == "CSV") {

Pattern 3:

Please modify as follows.

From:
 if (attachment.getContentType() === "text/csv") { 
To:
 var fileName = attachment.getName().toUpperCase().split("."); if (fileName.length > 1 && fileName[1] == "CSV") { 

Note:

  • About pattern 1, the mimeType is set from the extension of the filename by using setContentTypeFromExtension() .
  • About pattern 2, if in your environment, CSV files are retrieved as other mimeType, please modify application/vnd.ms-excel .
  • About pattern 1 and 3, if the filename of CSV file has not extension or other extension, it cannot be used under the situation.

Reference:

If these were not what you want, I'm sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM