read data from csv-like file in Google Apps Script

2019-05-29 02:31发布

问题:

I have a Windows script file (not a Google Apps Script though) that outputs data to a text file. This file has numbers separted by commas (like a CSV file but is created programatically). I can open this in Excel as a CSV file. This file is stored on my Google Drive. I want to write a Google Appscript that runs each day and opens this text file with numbers separated by commas and displays the data in an Appscript chart.

In Apps Script, How to read in the data from this text file? It looks like the SpreadsheetApp does not work with on a text file with data separated by commas but rather only on Google Sheets files. Is this true? How can I read in this data from from my text file with numbers separated by commas?

回答1:

you could look at something like that:

function parseCsv (file, ss) {
  var data = file.getBlob().getDataAsString();
  var lines = data.split("\n");
  var data = lines.map(function(lin){return lin.split(",")});
  var dest = ss.getActiveSheet();
  dest.clear();
  dest.getRange(1, 1, data.length, data[0].length).setValues(data);
}

where file is your csv file that you retrieved with something like DriveApp.getFileById(id); and ss is a spreadsheet where you want your result



回答2:

Apart from the answers above, you could also use the inbuilt CSV parser from Utilities within GAS: GAS-parseCsv