Pull specific columns from Gmail CSV attachment to Google sheet using app script

226 views
Skip to first unread message

Shubham Gupta

unread,
Aug 31, 2022, 1:52:42 PM8/31/22
to Google Apps Script Community

I'm using an automated script which helps me pull a Gmail CSV attachment into a spreadsheet, but I want to parse only specific columns rather than the entire CSV file. Would be a great help if you can help here.

Here is the script:


function getattach(){


var threads = GmailApp.search('Daily Hunting file has:attachment newer_than:1d');

var messages = threads[0].getMessages();

var attach = messages[0].getAttachments();

var timestamp = messages[0].getDate();
    
    for (var i = 0; i < attach.length; ++i) {
    
      var data = attach[i].copyBlob();
      var name = data.getName();
      
      var result = name.indexOf('report.csv');
      if (name.indexOf('report.csv')>-1) {
          var csvData = Utilities.parseCsv(data.getDataAsString());
      } //end if
    
    } //end for
       
    return csvData;

}


function updateSheet() {

    var ss = SpreadsheetApp.getActive();
    var ImportSheet = ss.getSheetByName('Import');
    
    var ImportData = getattach();

    //Write results to the Sheet

    var lastRow = ImportSheet.getLastRow();
    if (lastRow < 1) lastRow = 1;
    ImportSheet.getRange(1,1,lastRow, ImportData[0].length).clearContent();
  ImportSheet.getRange(1,1,ImportData.length, ImportData[10].length).setValues(ImportData);
   
 } 

The above script works fine for me with no errors during runtime but above script is returning me each column and row data from the CSV attachment and i want to limit columns not rows as per my need by changing some parameters into the above script. For instance in gmail CSV file, the data length is having 5 columns instead of pulling 5 columns from the above script i want to pull only 2 columns to the source sheet. Let me know if this makes sense?


Tanaike

unread,
Aug 31, 2022, 9:57:16 PM8/31/22
to Google Apps Script Community
In your script, how about the following modification?

From

return csvData;

To

var retrieveColumns = [1, 3, 5]; // This is the column numbers. In this sample, those are "A", "C", and "E".
return csvData.map(r => retrieveColumns.length > 0 ? retrieveColumns.map(n => r[n - 1] || "") : r);


And, in this case, in "updateSheet()" function, please modify as follows.

From

ImportSheet.getRange(1, 1, ImportData.length, ImportData[10].length).setValues(ImportData);

To

ImportSheet.getRange(1, 1, ImportData.length, ImportData[0].length).setValues(ImportData);


Reply all
Reply to author
Forward
0 new messages