Google Sheets API: How to "Publish on the Web" for an embedded sheet?

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

  • Go to Google Drive.
  • Open table
  • File> Publish on the Internet> Paste> Copy generated iframe link to html file

How could I programmatically achieve the above via the Google Sheets API using front-panel JavaScript? I create spreadsheets "on the fly" in my application and I want to immediately embed them on the created page.

After creating the sheet, I can dynamically create the iframe element with the necessary attributes (sheet ID, among other things). This generates an error. From this question, it looks like there should be an attribute on the sheet published: trueor something like that, but this requires using the Drive API - I try to avoid that. Is it possible to process only through the table API?

+4
source share
2 answers

API- , , API- Drive . , . , - !

script Google JS- index.html:

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

JS:

// Cache the api 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));
  });
});
+4

, API API- Drive ( PATCH https://www.googleapis.com/drive/v3/files/fileId/revisions/revisionId, https://developers.google.com/drive/v3/reference/revisions/update).

+1

Source: https://habr.com/ru/post/1648829/


All Articles