繁体   English   中英

如何使用应用脚本从 Gmail CSV 附件中提取特定列到 Google 电子表格?

[英]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. 如果您可以在这里提供帮助,那将是一个很大的帮助这里是脚本:

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);

}

从 csv 文件中获取列

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

文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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