Gspread将电子表格导出到带有格式的文件系统

时间:2015-10-15 16:39:15

标签: python django gspread

我需要在文件系统上下载Google电子表格,我正在使用Gspread来阅读Google云端硬盘中的文件。该程序正常运行。

我尝试导出为CSV,但这会丢弃格式化。

    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())  

我想知道我是否可以做这样的事情

worksheet.export("/myFolder")

1 个答案:

答案 0 :(得分:1)

尝试导出到.XLSX文件。格式将被保留:

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()