How to Convert Google Documents and Spreadsheets with Apps Script

Advertisements

With Google Apps Script, you can simply convert any Google Spreadsheet or Google Document in your Google Drive to other formats such as PDF, XLS, and so on, and then email or save the converted file back to Google Drive.

If you want a simpler way that does not require you to create any Google Apps Script code, you may acquire the Email Google Spreadsheet add-on.

Save Google Document as HTML file

// Credit Stéphane Giron

function exportAsHTML(documentId) {
  var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
  var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + documentId + '&exportFormat=html';
  var param = {
    method: 'get',
    headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
    muteHttpExceptions: true,
  };
  var html = UrlFetchApp.fetch(url, param).getContentText();
  var file = DriveApp.createFile(documentId + '.html', html);
  return file.getUrl();
}

Export Google Spreadsheet as Microsoft Excel format

// Credit: Eric Koleda

function exportAsExcel(spreadsheetId) {
  var file = Drive.Files.get(spreadsheetId);
  var url = file.exportLinks['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + token,
    },
  });
  return response.getBlob();
}

Advertisements

Leave a Comment