django Gspread导出电子表格到文件系统与格式化

mqkwyuun  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(103)

我需要下载文件系统上的谷歌电子表格,我使用Gspread从谷歌驱动器读取文件,工作正常。
我尝试导出到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")
eyh26e7m

eyh26e7m1#

尝试导出为.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()
vfwfrxfs

vfwfrxfs2#

这是一个工作版本。

import gspread
from gspread.utils import ExportFormat

gc = gspread.service_account(filename=KEY_FILE) #json key service account
workbook = gc.open_by_url(SPREADSHEET_URL)
export_file = workbook.export(format=ExportFormat.EXCEL)
with open('output.xlsx', 'wb') as f:
   f.write(export_file)

你也可以在这里使用:

  • ExportFormat.PDF
  • ExportFormat.EXCEL
  • ExportFormat.CSV
  • 导出格式.OPEN_OFFICE_SHEET
  • ExportFormat.TSV
  • 导出格式.ZIPPED_HTML

相关问题