4

I need to convert Excel files already uploaded to Google Drive into Google's spreadsheet format. What is the best way to do that programmatically?

I've found this post (#15), but I can't figure out how to use this code. And it seems intended for Excel files not already stored on Drive. Uploading it again would be redundant.

Cutter
  • 1,673
  • 7
  • 27
  • 43

3 Answers3

3

For those that stumble upon this: This is possible in both Drive API v2 & v3. Python example:

API v2:

drive_service_v2.files().copy(body=body, fileId="0n3xrtmjFpuG3V1g3h24tVHM2a33", convert="true").execute()

API v3:

new_mime_type = "application/vnd.google-apps.spreadsheet"
file_id_of_Excel_file = "0n3xrtmjFpuG3V1g3h24tVHM2a33"
body = {'name': 'New File Name', 'mimeType': new_mime_type}        
drive_service.files().copy(body=body, fileId=file_id_of_Excel_file).execute()
parapet
  • 69
  • 3
2

Unfortunately you cannot convert a file in-place, and you'll need to re-upload it. Here's a sample showing how to use an XLSX file already in your drive:

function convert(xlsxFileId) { 
  var xlsxBlob = DriveApp.getFileById(xlsxFileId).getBlob();
  var file = {
    title: 'Converted Spreadsheet'
  };
  file = Drive.Files.insert(file, xlsxBlob, {
    convert: true
  });
}
Eric Koleda
  • 12,420
  • 1
  • 33
  • 51
  • It works, thanks! But can you explain the `insert` method's usage? Is it the same method as described [here](https://developers.google.com/drive/v2/reference/files/insert#examples)? Why aren't the parameters you used described there? – Cutter May 01 '14 at 16:58
  • Yes, that's the same method. Apps Script orders the parameters slightly differently though, namely: resource, requiredArgs, mediaData, optionalArgs – Eric Koleda May 01 '14 at 18:02
  • For some reason this code doesn't work anymore... The generated file is an empty XLS one of 0 bytes size. I still have the Drive API enabled. But in the script execution log, there is this line: `[14-05-01 23:55:30:289 CEST] File.getBlob() [0 secondes]` Obviously the getBlob() method doesn't work anymore. How can I troubleshoot this? – Cutter May 01 '14 at 21:56
  • ... and it works back again (I didn't change the code nor my Drive contents). Any idea what might have caused the problem? – Cutter May 02 '14 at 07:51
2

In Google Driver V3 API, just need to set MimeType.

File file = new File();

file.MimeType = "application/vnd.google-apps.spreadsheet"
Vinoth Vino
  • 9,166
  • 3
  • 66
  • 70
Paul Xia
  • 21
  • 1