简体   繁体   中英

How to pull specific columns from Gmail CSV attachment to Google Spreadsheet using app script?

I'm using an automated script which helps me to pull the gmail csv attachment to the spreadsheet but i want to parse only specific columns instead of entire report format from csv file that i'm getting in my gmail inbox. 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);

}

Getting a column from a csv file

function getColumnFromCSV(id="file id",col=9) {
  const file = DriveApp.getFileById(id)
  const a = Utilities.parseCsv(file.getBlob().getDataAsString());
  let o = a.map(r => r[col - 1]).flat()
  Logger.log(JSON.stringify(o))
}

Execution log
1:19:20 PM  Notice  Execution started
1:19:21 PM  Info    ["COL9","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28"]
1:19:22 PM  Notice  Execution completed

File:

COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10
1,2,3,4,5,6,7,8,9,10
2,3,4,5,6,7,8,9,10,11
3,4,5,6,7,8,9,10,11,12
4,5,6,7,8,9,10,11,12,13
5,6,7,8,9,10,11,12,13,14
6,7,8,9,10,11,12,13,14,15
7,8,9,10,11,12,13,14,15,16
8,9,10,11,12,13,14,15,16,17
9,10,11,12,13,14,15,16,17,18
10,11,12,13,14,15,16,17,18,19
11,12,13,14,15,16,17,18,19,20
12,13,14,15,16,17,18,19,20,21
13,14,15,16,17,18,19,20,21,22
14,15,16,17,18,19,20,21,22,23
15,16,17,18,19,20,21,22,23,24
16,17,18,19,20,21,22,23,24,25
17,18,19,20,21,22,23,24,25,26
18,19,20,21,22,23,24,25,26,27
19,20,21,22,23,24,25,26,27,28
20,21,22,23,24,25,26,27,28,29

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