Lit*_*ito 4 google-apps-script google-drive-api
我们的服务器上有 CSV 文件,https://example.com/thisFIle.csv。这是从 Google Sheet 导出的数据。第三方网站每 3 分钟从该 CSV 文件获取一次数据。
我工作的公司是做预订业务的,所以他们的代理就是更新Google表格的人,然后我会将数据导出为CSV,然后上传到我们的服务器。
经过搜索,我了解到 Google Sheet 中有这个 google script 部分。我如何才能使用此谷歌脚本自动导出 CSV 然后手动上传到我们的服务器?
是的,您可以使用 Google App Script [1] 来实现该过程。
使用电子表格服务[2]和[3]中的类的方法,您可以获得您想要的具有电子表格ID(打开Google表格时出现在URL中的字母数字ID)的工作表的数据。然后循环数据并将其解析为csv格式的字符串。
使用 csv 字符串,您可以创建一个 blob 对象 [4],该对象将使用 fetch 方法 [5] 通过 post 请求发送到服务器。
例如,要使代码自动运行,您可以使用手动触发器,并将它们设置为每分钟运行一次或根据需要运行 [6]。
您必须将服务器应用程序设置为接收 post 请求,并在应用程序脚本中设置请求 url(以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': csvBlob
};
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch('https://example.com/post', options);
}
Run Code Online (Sandbox Code Playgroud)
[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
归档时间: |
|
查看次数: |
7085 次 |
最近记录: |