Google表格API:如何“发布到网络”为嵌入式表? [英] Google Sheets API: How to "publish to web" for embeddable sheet?

查看:94
本文介绍了Google表格API:如何“发布到网络”为嵌入式表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想发布Google表格电子表格,以便将其嵌入到iframe中的页面上,我会手动执行以下操作:

If I wanted to publish a Google Sheets spreadsheet so I could embed it on a page within an iframe, I would manually do the following:



  1. 打开电子表格

  2. 文件>发布到网络>嵌入>将生成的iframe链接复制到html文件中

如何通过前端的JavaScript使用Google Sheets API以编程方式实现上述目标?我在应用程序中即时生成电子表格,并希望立即将它们嵌入到创建后的页面中。

How would I programmatically achieve the above through the Google Sheets API using JavaScript on the front end? I'm generating spreadsheets on the fly in my application and want to immediately embed them on the page once created.

创建表格后,我可以动态创建iframe具有必要属性的元素(表单ID等)。这会引发错误。从这个问题,它看起来像就像一张表需要一个发表:true 属性或者其他内容,但这需要使用Drive API - 我试图避免这种情况。是否可以通过Sheets API处理

Once the sheet is created, I can dynamically create an iframe element with the necessary attributes (the sheets ID, among others). That throws an error. From this question, it looks like a sheet needs to have a published: true attribute or something, but that requires using the Drive API - I'm trying to avoid that. Is this possible to handle only through the Sheets API?

推荐答案

搜索整个Sheets API ,谷歌搜索,只是一般的灵魂搜索,我别无选择,只能包括Drive API并用它来做我的投标。这是我提出的解决方案。希望这可以帮助别人!

After searching through the entire Sheets API, googling, and just general soul-searching, I had no choice but to include the Drive API and use it to do my bidding. Here's the solution I came up with. Hope this helps someone else out there!

使用Google的这个脚本作为 index.html file:

Used this script from Google for the client-side JS library in the index.html file:

<body>
  ...
  <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
</body>

然后对于JS的东西:

Then for the JS stuffs:

// Cache the api's into variables.
var sheets = gapi.client.sheets;
var drive = gapi.client.drive;

// 1. CREATE NEW SPREADSHEET
sheets.spreadsheets.create({
  properties: {
    title: 'new-sheet'
  }
}).then(function(newSpreadSheet) {
  var id = newSpreadSheet.result.spreadsheetId;

  // 2. PUBLISH SPREADSHEAT VIA DRIVE API
  drive.revisions.update({
    fileId: id,
    revisionId: 1
  }, {
    published: true, // <-- This is where the magic happens!
    publishAuto: true
  }).then(function() {

    // 3. DISPLAY SPREADSHEET ON PAGE VIA IFRAME
    var iframe = [
      '<iframe ',
      'src="https://docs.google.com/spreadsheets/d/',
      id,
      '/pubhtml?widget=true&headers=false&embedded=true"></iframe>'
    ].join('');

    // We're using jQuery on the page, but you get the idea.
    $('#container').html($(iframe));
  });
});

这篇关于Google表格API:如何“发布到网络”为嵌入式表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆