Google Sheets API: How to “publish to web” for emb

2019-01-15 09:52发布

问题:

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. Navigate to Google Drive
  2. Open a spreadsheet
  3. File > Publish To Web > Embed > Copy the generated iframe link into an html file

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.

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?

回答1:

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!

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>

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));
  });
});


回答2:

As you have concluded, it is not possible through the Sheets API today and is only possible through the Drive API (using the PATCH https://www.googleapis.com/drive/v3/files/fileId/revisions/revisionId request, documented at https://developers.google.com/drive/v3/reference/revisions/update).