3

I need to download the Google spreadsheets on filesystem, I am using Gspread to read the files from Google Drive which works fine.

I tried exporting to CSV but this ofcourse discards the formatting.

    json_key = json.load(open('/googleDriveCredentials.json'))
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
    gc = gspread.authorize(credentials)
    wks = gc.openall()

    # processing first workbook
    spreadsheet = wks[1] 

    # Creating CSV file which doesn't preserve formatting
    for i, worksheet in enumerate(spreadsheet.worksheets()):
        filename = 'somefile' + str(i) + '.csv'
        with open(filename, 'wb') as f:
            writer = csv.writer(f)
            writer.writerows(worksheet.get_all_values())  

I am wondering if I can do something like this

worksheet.export("/myFolder")
mahaDev
  • 125
  • 3
  • 10

1 Answers1

1

Try exporting to a .XLSX file. The formatting will be preserved:

import gspread

gc = gspread.authorize(credentials)
sh = gc.open_by_url('your spreadsheet')
worksheet = sh.worksheet('your worksheet')
export_file = worksheet.export(format='xlsx')
f = open('filename.xlsx', 'wb')
f.write(export_file)
f.close()
  • 1
    The docs say this is no longer supported [here](https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.export), any alternative? – eudoxos Oct 24 '18 at 09:11