Using Google Apps Script to convert a Word document to Google Docs by jgn on Monday, September 9, 2024 in programming, hacks, Google Apps, and Google Apps Script

I recently wanted to write code to convert a Microsoft Word document to a Google Doc. (In fact, I wanted to convert many such Word docs.)

This turned out to be pretty obscure. Here's how to do it (ids changed):

function go() {
  convertWordDocToGoogleDoc(
    "15qYN30uJAsMhKxUb1nbCoE09NT7-FPZs",
    "Converted",
    "1-Grx_yhWWOA73-1dnbEI6JlfHkDXxzr6"
  );
}

function convertWordDocToGoogleDoc(sourceFileId, targetFileName, targetFolderId) {
  // Convert a Word doc to a Google doc
  // (this was a royal pain to figure out)
  let targetResource = {
    'name':     targetFileName,
    'mimeType': MimeType.GOOGLE_DOCS,
    'parents':  [targetFolderId]
  };
  // Notice: This is done with the *Drive* service, not the DocumentApp
  // To add the Drive Service, click the "+" by Services in the left-hand
  // pane and select Drive API.
  let targetFile = Drive.Files.copy(targetResource, sourceFileId);

  return targetFile.id;
};
comments powered by Disqus