ben890
ben890

Reputation: 1133

Add xlsx documents to Google Drive shared folder using Python

I'm able to add CSVs to a shared google drive folder using Python, but I'm confused as what to change in my script to allow for excel documents. Here is my code for CSV.

def publish_to_drive(folder_id, path_to_file, filename):
    SCOPES = ['https://www.googleapis.com/auth/drive']
    SERVICE_ACCOUNT_FILE = 'keys.json'
    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = discovery.build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': filename,
        'parents': [folder_id],
        'mimeType': 'text/csv'
    }
    media_body = MediaFileUpload(path_to_file, mimetype='text/csv', 
                                 resumable=True)
    resp = service.files().create(body=file_metadata, media_body=media_body,supportsAllDrives=True).execute()

I realize that the mimetypes need to be changed, but I'm not sure what they need to be changed to. I've tried various ones but have not been able to get the right ones.

Upon using the right mimetypes I get the following when attempting to open the excel file:

enter image description here

Upvotes: 1

Views: 354

Answers (1)

NightEye
NightEye

Reputation: 11214

If there isn't an issue on using function on text/csv file types, then I believe you only need to update your mimetype from text/csv into application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

I've added some resources/links below that lists other mime types if you need your function to work on them too.

To actually support multiple mime types, you need to dynamically identify the mimetype for each file type. You can do it by either:

  • Simple string manipulation (if you see a pattern) or have a conditional statement on each mimetype you want to support (both not recommended)
  • Or for universality, like this.

Resources:

Upvotes: 1

Related Questions