Google表格API:如何为嵌入式表格"发布到网络"?

The*_*ith 8 google-api google-sheets google-api-client google-sheets-api

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

  1. 导航到Google云端硬盘
  2. 打开电子表格
  3. 文件>发布到Web>嵌入>将生成的iframe链接复制到html文件中

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

创建工作表后,我可以动态创建具有必要属性的iframe元素(工作表ID等).这引发了一个错误.从这个问题来看,它看起来像一张表需要有一个published: true属性或东西,但这需要使用Drive API - 我试图避免这种情况.这是可能的处理只能通过Sheets API?

The*_*ith 13

在搜索整个表格API,谷歌搜索,以及一般的反省之后,我别无选择,只能包含Drive API并使用它来进行我的出价.这是我提出的解决方案.希望这有助于其他人!

使用Google的这个脚本为文件中的客户端JS库index.html:

<body>
  ...
  <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

那么对于JS的东西:

// 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));
  });
});
Run Code Online (Sandbox Code Playgroud)


Sam*_*lin 5

正如您所得出的结论,目前无法通过 Sheets API 实现这一点,只能通过 Drive API 实现(使用请求PATCH https://www.googleapis.com/drive/v3/files/fileId/revisions/revisionId,记录于https://developers.google.com/drive/v3/reference/revisions/update)。


归档时间:

查看次数:

3251 次

最近记录:

8 年,10 月 前