我们有CSV文件,该文件位于我们的服务器https://example.com/thisFIle.csv上。那就是从谷歌表导出的数据。第三方网站每3分钟从该CSV文件中获取数据。
我正在工作的公司正在预订业务,所以他们的代理商就是更新Google工作表的人员,然后我将数据导出为CSV,然后上传到我们的服务器。
在搜索时,我了解到Google表格中有此google脚本部分。我该如何代替导出CSV,然后手动使用此Google脚本将其手动上传到我们的服务器以进行自动处理?
答案 0 :(得分:2)
是的,您可以使用Google App脚本[1]完成该过程。
使用电子表格服务[2]和[3]中的类的方法,您可以获取想要具有工作表ID(在打开Google表格时显示在url中的ID)的工作表的数据。然后,我遍历数据并将其解析为csv格式的字符串。
使用csv字符串,您可以创建一个blob对象[4],该对象将使用fetch方法[5]通过发布请求发送到服务器。
要使代码自动运行,您可以使用手动触发器,例如,将它们设置为每分钟或根据需要运行[6]。
您必须将服务器应用程序设置为接收发布请求,并在App脚本中设置请求网址(我以https://example.com/post为例)。下面是我测试直到获得csvBlob变量的代码:
function myFunction() {
var ss = SpreadsheetApp.openById("SpreadsheetID");
var sheet = ss.getSheets()[0];
// This represents ALL the data
var range = sheet.getDataRange();
var values = range.getValues();
var csvStr = "";
// This creates a string of the spreadsheet in CSV format with a trailing comma
for (var i = 0; i < values.length; i++) {
var row = "";
for (var j = 0; j < values[i].length; j++) {
if (values[i][j]) {
row = row + values[i][j];
row = row + ",";
row = row.substring(0, (row.length-1));
csvStr += row + "\n";
}
//creates de Blob of the csv file
var csvBlob = Utilities.newBlob(csvStr, 'text/csv', 'example.csv');
Logger.log(csvBlob.getDataAsString());
//make a post request to the server (I didn't test this part)
var formData = {
'name': 'Bob Smith',
'email': 'bob@example.com',
'file': csv
};
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch('https://example.com/post', options);
}
[1] https://script.google.com/home
[2] https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app
[3] https://developers.google.com/apps-script/reference/spreadsheet/sheet
[4] https://developers.google.com/apps-script/reference/utilities/utilities#newBlob(Byte,String,String)
[5] https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
[6] https://developers.google.com/apps-script/guides/triggers/installable