【问题标题】:automatically export CSV from googlesheet to our server自动将 CSV 从 google sheet 导出到我们的服务器
【发布时间】:2019-06-20 06:32:10
【问题描述】:

我们的服务器上有 CSV 文件,https://example.com/thisFIle.csv。那是从谷歌表导出的数据。第三方网站每 3 分钟从该 CSV 文件中获取数据。

我工作的公司是做预订业务的,所以他们的代理是更新谷歌表格的人,然后我会把数据导出成CSV然后上传到我们的服务器。

通过搜索,我了解到 Google 表格中有这个 google 脚本部分。我怎样才能使导出 CSV 然后手动上传到我们的服务器以自动使用此 google 脚本的过程?

【问题讨论】:

  • 我认为可以使用 Google Apps 脚本将电子表格导出为 CSV 文件。但我无法理解你在想的automatically。我为我糟糕的英语水平道歉。可以问一下automatically的详细情况吗?
  • 谷歌应用脚​​本中是否还有一种方法可以将导出的 csv(使用该谷歌应用脚​​本)上传到我们的服务器?因为场景是,一些第三方系统正在从该 csv 中获取数据,所以我们需要在每次谷歌表上有变化时更新它。
  • 感谢您的回复。我注意到已经发布了答案。我认为它会解决您的问题。

标签: google-apps-script google-drive-api


【解决方案1】:

是的,您可以使用 Google 应用脚本 [1] 实现该过程。

使用电子表格服务 [2] 和 [3] 中的类的方法,您可以获得具有电子表格 ID(打开 Google 表格时出现在 url 中的字母数字 ID)的表格数据.然后循环遍历数据,解析成csv格式的字符串。

使用 csv 字符串,您可以创建一个 blob 对象 [4],该对象将使用 fetch 方法 [5] 通过发布请求发送到服务器。

要使您的代码自动运行,您可以使用手动触发器,例如,将它们设置为每分钟运行一次或根据需要运行 [6]。

您必须设置您的服务器应用程序以接收发布请求并在应用脚本中设置请求 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);
}

[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

【讨论】:

  • 感谢@AndresDuarte!我会试试这个,让你知道结果
猜你喜欢
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 2022-07-15
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
相关资源
最近更新 更多