Home > Software engineering >  How to get All versions' data in Google sheet?
How to get All versions' data in Google sheet?

Time:05-06

I have a Google sheet which has a large number of versions. Now, I want to get each version one by one, extract data of that version into Google sheet. I have tried to follow the below solution from @Tanaike:

function myFunction() {
  var spreadsheetId = "###"; // Please set the Spreadsheet ID.
  var revisionId = "###"; // Please set the revision ID.

  var url = "https://docs.google.com/spreadsheets/export?id="   spreadsheetId   "&revision="   revisionId   "&exportFormat=xlsx";
  var blob = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer "   ScriptApp.getOAuthToken()}}).getBlob();
  var id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: revisionId}, blob).id;


  var spreadsheet = SpreadsheetApp.openById(id);
  var sheet = spreadsheet.getSheets()[0];
  var sheetdata = sheet.getDataRange().getValues();
}

It would be helpful if you can guide me/suggest it to me about it. I just want to get all the data for each version history and put it into Google sheets. Thank you for your guidance.

CodePudding user response:

Following the advice in the comments. The sample code requires the revision ID. A sample code to gather all the revisions ID:

function listRevisions(fileId) {
  var fileId = 'yourfileid';
  var revisions = Drive.Revisions.list(fileId);

  if (revisions.items && revisions.items.length > 0) {
    for (var i = 0; i < revisions.items.length; i  ) {
      var revision = revisions.items[i];
      var date = new Date(revision.modifiedDate);
      Logger.log(revision.id);
    }
  } else {
   Logger.log('No revisions found.');
  }
}

  1. Get the File ID of the Spreadsheet that you want to get its revision (the one you would be adding in the first sample code)

  2. Revisions: list, you can get here the list of all revision that you do for that file in particular and is presented in the sample code above or you can manually test it over the web

  3. By using Revisions: get, you should be able to get an specific revision details of the file by adding both the file id and revision id.

There is also an excellent thread with information about it where the sample code was taken (besides the ones linked in the revision list official documentation, there are javascript samples that can also be used) feel free to review the thread

  • Related