简体   繁体   English

REST API Google表格-在客户端JS中使用

[英]REST API Google Sheets - use from client JS

Is there any way how to use google sheets for write and read data directly from client javascript in a web browser? 有什么方法可以使用Google表格在网络浏览器中直接从客户端JavaScript直接写入和读取数据吗?

Data security is no issue here. 数据安全在这里不是问题。 I just need some small free database for single page web application without web server. 我只需要一些免费的小型数据库,即可安装没有Web服务器的单页Web应用程序。

Yes, there is a way. 是的,有办法。 Sometimes i use google sheet to save form data. 有时我用谷歌表来保存表格数据。 So i wont give you full solution, but it could be good starting point. 所以我不会给您完整的解决方案,但这可能是一个很好的起点。

  • Create or open a spreadsheet in Google Sheets. 在Google表格中创建或打开电子表格。
  • Select the menu item Tools > Script editor. 选择菜单项“工具”>“脚本编辑器”。 If you are presented with a welcome screen, click Blank Project on the left to start a new project. 如果出现欢迎屏幕,请单击左侧的空白项目以启动新项目。
  • Delete any code in the script editor. 在脚本编辑器中删除任何代码。 And simply copy and paste the code into the script editor: 只需将代码复制并粘贴到脚本编辑器中:

 // 1. Enter sheet name where data is to be written below var SHEET_NAME = "Sheet1"; // 2. Run > setup // // 3. Publish > Deploy as web app // - enter Project Version name and click 'Save New Version' // - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously) // // 4. Copy the 'Current web app URL' and post this in your form/script action // // 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case) var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service // If you don't want to expose either GET or POST methods you can comment out the appropriate function function doGet(e){ return handleResponse(e); } function doPost(e){ return handleResponse(e); } function handleResponse(e) { // shortly after my original solution Google announced the LockService[1] // this prevents concurrent access overwritting data // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html // we want a public lock, one that locks for all invocations var lock = LockService.getPublicLock(); lock.waitLock(30000); // wait 30 seconds before conceding defeat. try { // next set where we write the data - you could write to multiple/alternate destinations var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key")); var sheet = doc.getSheetByName(SHEET_NAME); // we'll assume header is in row 1 but you can override with header_row in GET/POST data var headRow = e.parameter.header_row || 1; var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var nextRow = sheet.getLastRow()+1; // get next row var row = []; // loop through the header columns for (i in headers){ if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column row.push(new Date()); } else { // else use header name to get data row.push(e.parameter[headers[i]]); } } // more efficient to set values as [][] array than individually sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // return json success results return ContentService .createTextOutput(JSON.stringify({"result":"success", "row": nextRow})) .setMimeType(ContentService.MimeType.JSON); } catch(e){ // if error return this return ContentService .createTextOutput(JSON.stringify({"result":"error", "error": e})) .setMimeType(ContentService.MimeType.JSON); } finally { //release lock lock.releaseLock(); } } function setup() { var doc = SpreadsheetApp.getActiveSpreadsheet(); SCRIPT_PROP.setProperty("key", doc.getId()); } 

  • Publish > Deploy as web app. 发布>部署为Web应用程序。
  • Choose your security options. 选择您的安全性选项。 And press "Deploy" 然后按“部署”
  • Now URL will be generated for you, in my case this URL is: https://script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exe 现在将为您生成URL,在我的情况下,该URL为: https : //script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exe
  • Before using your link don't forget to Run > Setup. 使用链接之前,请不要忘记运行“运行”>“设置”。
  • Finaly you can send data to your sheet by post'ing form data to your URL. 最后,您可以通过将表单数据发布到URL将数据发送到工作表。 And first line of your sheet should contain names of fields what your are planing to save. 工作表的第一行应包含您计划保存的字段名称。 In this case write in A1: Name, in B1: Mail and in C1-> Comment. 在这种情况下,请在A1:名称,B1:邮件和C1->注释中输入。

  <form id="form" action="YOUR_URL"> <label>Name</label><br /> <input name="Name" type="text" value="" /><br /> <label>Email</label><br /> <input name="Email" type="text" value="" /><br /> <label>Comment</label><br /> <textarea name="Comment" /><br /> <input type="submit" value="Send" /> </form> 

Now you can send data with javascript to your URL. 现在,您可以使用javascript将数据发送到您的URL。 If you look closely at the url, you will be able to find the spreadsheet's key. 如果您仔细查看网址,则可以找到电子表格的密钥。 My document key is: 10vmpPMTBqsXYsTH20a_kU-GTJ06KYxXWg-E2aAtm_dM 我的文档密钥是:10vmpPMTBqsXYsTH20a_kU-GTJ06KYxXWg-E2aAtm_dM

The JSON feeds for any Google Spreadsheet is available at: 可通过以下网址获取任何Google Spreadsheet的JSON供稿:

JSON Format: https://spreadsheets.google.com/feeds/list/YOUR_KEY/od6/public/basic?alt=json JSON格式: https//spreadsheets.google.com/feeds/list/YOUR_KEY/od6/public/basic? alt = json

And of cause your document should be published before accessing JSON URL. 因此,应该在访问JSON URL之前发布您的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM