我每小时在Google云端硬盘中收到一个新的CSV文件。 在Google云端硬盘文件夹中收到电子表格后,我需要使用最新CSV文件中的数据更新电子表格。
根据日期和时间,进入该文件夹的文件对于每个新文件都有一个唯一的名称。 例如:FileName_date_24hourtime.csv FileName_20190524_1800.csv,然后FileName_20190524_1900.csv等。
首先,我不确定最好的方法是什么
仅带有一个公式(可能不知道确切的文件名就不可能?),例如= IMPORTDATA
一个Google脚本,用于查找最新的.csv文件并在文件添加到Google云端硬盘文件夹后自动导入
任何帮助都会很棒!
.csv文件: .csv文件包含28行,数据应按分割; .csv文件如下所示: 名称; -63.06; -58.08; 50.62; -66.67; -80.00 名称; -61.82; -56.83; -50.55; -77.78; -70.00 名称; -57.77; -50.21; 52.88; -77.78; -70.00 NAME1; -57.69; -61.48; -55.59; -55.56; -60.00 NAME2; -61.62; -53.79; 50.34; -66.67; -70.00 NAME3; -54.62; -54.57; -52.22; 55.56; -60.00 ...总共28行
数据应转到“导入统计信息”表。
答案 0 :(得分:0)
最好的方法是使用带有触发器的脚本,该触发器具有执行将数据导入电子表格的功能。
创建具有1小时偏移的基于时间的触发器:
function trigger() {
var trg = ScriptApp.newTrigger('checkFiles');
trg.timeBased().everyHours(1).create();
}
创建用于检查文件夹中文件(例如“ checkFiles”)的功能。
function checkFiles(alreadyWaited) {
//get spreadsheet and sheet;
var id = 'yourSpreadsheetId';
var ss = SpreadsheetApp.openById(id);
var sh = ss.getSheetByName('Import_Stats');
var folderId = 'yourIdHere'; //folder by id is the simplest way;
//get folder and files in it;
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFilesByType('text/csv');
var filesImport = folder.getFilesByType('text/csv'); //fetch files again;
//try to fetch number of files;
var scriptProps = PropertiesService.getScriptProperties();
var numFiles = scriptProps.getProperty('numFiles');
//count current number of files;
var numCurr = 0;
while(files.hasNext()) {
var f = files.next();
numCurr++;
}
//if this is the first time, save current number;
if(numFiles===null) {
scriptProps.setProperty('numFiles',numCurr);
}else {
numFiles = parseInt(numFiles);
}
if(numFiles===null||numFiles===(numCurr-1)) {
//get today and reset everything except hours;
var today = new Date();
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
//iterate over files;
while(files.hasNext()) {
var file = files.next();
//get file creation date and reset;
var created = file.getDateCreated();
created.setMinutes(0);
created.setSeconds(0);
created.setMilliseconds(0);
//calculate offset, equals 0 for each file created this hour;
var offset = today.valueOf()-created.valueOf();
if(offset===0) {
//perform data import here;
var data = file.getBlob().getDataAsString();
//ignore empty files;
if(data!=='') {
//split data in rows;
var arr = data.split('\r\n');
//resplit array if only one row;
if(arr.length===1) {
arr = data.split('\n');
}
//append rows with data to sheet;
arr.forEach(function(el){
el = el.split(';');
sh.appendRow(el);
});
}
}
}
}else {
//if never waited, set minute to wait, else add minute;
if(!alreadyWaited) {
alreadyWaited = 60000;
}else {
alreadyWaited += alreadyWaited;
}
//if waited for 10 minutes -> end recursion;
if(alreadyWaited===600000) {
Logger.log('Waited 10 minutes but recieved no files!');
return;
}
//wait a minute and recheck;
Utilities.sleep(60000);
return checkFiles(alreadyWaited);
}
}
这应该发生: