且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过cURL / PHP将新行插入Google Spreadsheet - 如何?

更新时间:2023-12-04 13:36:10


我不认为我可以使用t他的Google Apps脚本,因为我看不到我如何通过PHP脚本进行编码和触发。


当然可以。您可以使用Google Apps脚本创建Web服务,该服务可以接收和处理服务请求。将参数传递给Web服务很简单,例如,可以使用cURL完成。



以下示例适用于包含两列的简单电子表格。您可以通过以下方式添加更多行:

  curl -L< SCRIPT URL>?col1 ='列1的值'& col2 ='另一个值'

或浏览器网址:

  https://< SCRIPT URL>?col1 ='列1的值'& col2 ='另一个值'

此示例电子表格已发布 here ,下面是一个可用于添加行的示例网址:

  https://script.google.com/macros/s/AKfycbzVDFmOeaQc4mDZhWCnwf0CUnX64YNhh_lTYhqtpBraINUf9e/exec?col1='Value for column 1'& col2 ='Another value'



说明



以下是一步一步的介绍。


  1. 打开Goog​​le电子表格,确保电子表格可以完全访问(公开) - >脚本编辑器

  2. 复制以下代码并粘贴到编辑器中

  3. 替换 - spreadsheet-id -

  4. 文件 - >保存

  5. 发布 - >部署为web- app - > Version = NEW;根据需要设置访问权限

  6. 授权(将提示您输入信用) - > DEPLOY

  7. 您现在将获得脚本的URL
  8. >
  9. 追加?col1 ='Colum1Data'& col2 ='Colum2Data'到URL中或根据需要进行编辑以将数据推送到电子表格URL

  10. 完成

(感谢vr00n。)



Code.gs



这可以是独立的或容器绑定的脚本;无论哪种方式,您都需要提供电子表格的ID,因为Web应用程序不会在电子表格上下文中运行。它不是显示HTML,而是使用 ContentService来提供简单文本 - 您可以详细说明任何适合您应用程序的方式。

 函数doGet(e){
Logger.log(JSON.stringify (e)); //查看参数

var result ='Ok'; //假定成功

if(e.parameter == undefined){
result ='No Parameters';
}
else {
var id ='--spreadsheet-id--'; // Spreadsheet id
var sheet = SpreadsheetApp.openById(id).getActiveSheet();
var newRow = sheet.getLastRow()+ 1;
var rowData = [];
for(var param in e.parameter){
Logger.log('for for loop,param ='+ param);
var value = stripQuotes(e.parameter [param]);
//Logger.log(param +':'+ e.parameter [param]);
switch(param){
case'col1':
rowData [0] = value;
休息;
case'col2':
rowData [1] = value;
休息;
默认值:
result =不支持的参数;
}
}
Logger.log(JSON.stringify(rowData));

//将新行写入电子表格
var newRange = sheet.getRange(newRow,1,1,rowData.length);
newRange.setValues([rowData]);
}

//返回操作结果
return ContentService.createTextOutput(result);
}

/ **
*删除首尾单引号或双引号
* /
函数stripQuotes(value){
return value.replace(/ ^ ['] | ['] $ / g,);您应该仔细阅读Google的Content Service文档,尤其是重定向的注意事项,以及敏感信息。

Is there a script or tutorial on how to do this? How to implement inserting of data from my PHP application into a Google Spreadsheet?

I've looked at the API (https://developers.google.com/google-apps/spreadsheets/) and there are no PHP codes/examples.

I've tried the Zend Library implementation, but something seems very outdated with that approach as I am getting some silly errors on a simple row insert.

I don't think I can use the Google Apps Script (https://developers.google.com/apps-script/reference/spreadsheet/) as I don't see how I can code and trigger from a PHP script.

Anything else?

Isn't there a workable API for this that we can easily use and tap into?

I don't think I can use the Google Apps Script as I don't see how I can code and trigger from a PHP script

Sure you can. You can create a web service using Google Apps Script, that can receive and process service requests. It's simple to pass parameters to the web service, this could be done using cURL, for instance.

The following example is for a simple spreadsheet with two columns. You can add further rows by:

curl -L <SCRIPT URL>?col1='Value for column 1'&col2='Another value'

or by browser URL:

https://<SCRIPT URL>?col1='Value for column 1'&col2='Another value'

This example spreadsheet is published here, and below is an example URL that can be used to add a row:

https://script.google.com/macros/s/AKfycbzVDFmOeaQc4mDZhWCnwf0CUnX64YNhhnKIlTYhqtpBraINUf9e/exec?col1='Value for column 1'&col2='Another value'

Instructions

Here is a step-by-step.

  1. Open a Google spreadsheet, ensure that the spreadsheet is fully accessible (public)
  2. Tools --> Script Editor
  3. Copy code below and paste into editor
  4. Replace the --spreadsheet-id-- with your sheet's id (easy to find this)
  5. File --> Save
  6. Publish --> Deploy as web-app --> Version = NEW ; set access as needed
  7. Authorize (will prompt you for creds) --> DEPLOY
  8. You will now get a URL to the script
  9. Append ?col1='Colum1Data'&col2='Colum2Data' to the URL or edit as needed to push data to the spreadsheet from the URL
  10. DONE

(Thanks to vr00n.)

Code.gs

This could be a stand-alone or container-bound script; either way, you need to supply the ID of the spreadsheet, since the web app does not run within a spreadsheet context. Rather than display html, it uses the ContentService to serve simple text - you can elaborate that in any way that is appropriate for your application.

function doGet(e) {  
  Logger.log( JSON.stringify(e) );  // view parameters

  var result = 'Ok'; // assume success

  if (e.parameter == undefined) {
    result = 'No Parameters';
  }
  else {
    var id = '--spreadsheet-id--'; // Spreadsheet id
    var sheet = SpreadsheetApp.openById(id).getActiveSheet();
    var newRow = sheet.getLastRow() + 1;
    var rowData = [];
    for (var param in e.parameter) {
      Logger.log('In for loop, param='+param);
      var value = stripQuotes(e.parameter[param]);
      //Logger.log(param + ':' + e.parameter[param]);
      switch (param) {
        case 'col1': 
          rowData[0] = value;
          break;
        case 'col2':
          rowData[1] = value;
          break;
        default:
          result = "unsupported parameter";
      }
    }
    Logger.log(JSON.stringify(rowData));

    // Write new row to spreadsheet
    var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
    newRange.setValues([rowData]);
  }

  // Return result of operation
  return ContentService.createTextOutput(result);
}

/**
 * Remove leading and trailing single or double quotes
 */
function stripQuotes( value ) {
  return value.replace(/^["']|['"]$/g, "");
}

You should read over Google's Content Service documentation, especially the cautions around redirection, and sensitive information.