Convert Word, Excel and PowerPoint files to Google Docs with Google Script

You can store your Microsoft Office files (Word Documents, PowerPoint Presentations and Excel Spreadsheets) in Google Drive in their native format but then it takes up storage space, the files cannot be edited in the cloud and you’ll not be able to embed the files on other web page.

For instance, you can embed a Google Sheet, or a portion of it, in your web page but not if the file is in the xls or xlsx format. A simple solution therefore would be to convert the Office documents into the corresponding Google Document formats and this can be easily done with Google Apps Script.

This Google Script will convert Office files to the Google format using the Advanced Drive API. It then renames the converted document to the original filename but without the extension. You will have to enable the Advance Drive API for your Apps Script project through the Google Developers Console.


// Written by Amit Agarwal www.ctrlq.org
// Email: amit@labnol.org

function convertDocuments() {
  
  // Convert xlsx file to Google Spreadsheet
  convertToGoogleDocs_("Excel File.xlsx")

  // Convert .doc/.docx files to Google Document
  convertToGoogleDocs_("Microsoft Word Document.doc")

  // Convert pptx to Google Slides
  convertToGoogleDocs_("PowerPoint Presentation.pptx")

}

// By Google Docs, we mean the native Google Docs format
function convertToGoogleDocs_(fileName) {
  
  var officeFile = DriveApp.getFilesByName(fileName).next();
  
  // Use the Advanced Drive API to upload the Excel file to Drive
  // convert = true will convert the file to the corresponding Google Docs format
  
  var uploadFile = JSON.parse(UrlFetchApp.fetch(
    "https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true", 
    {
      method: "POST",
      contentType: officeFile.getMimeType(),
      payload: officeFile.getBlob().getBytes(),
      headers: {
        "Authorization" : "Bearer " + ScriptApp.getOAuthToken()
      },
      muteHttpExceptions: true
    }
  ).getContentText());
  
  // Remove the file extension from the original file name
  var googleFileName = officeFile.substr(0, officeFile.lastIndexOf("."));
  
  // Update the name of the Google Sheet created from the Excel sheet
  DriveApp.getFileById(uploadFile.id).setName(googleFileName);
  
  Logger.log(uploadFile.alternateLink);  
}

The files are created the root folder of Google Drive.