如何通过Python结合Google Sheet API将谷歌表格导出为XLSX格式?
把谷歌表格导出为XLSX格式的解决方案
嘿,我来帮你搞定这个问题!你当前的代码用gsheets库导出CSV没问题,但要导出XLSX的话,我们可以借助pandas来实现——因为gsheets本身没有直接导出XLSX的方法,但它能把工作表数据转换成pandas的DataFrame,而pandas支持直接保存为XLSX格式。
步骤1:安装必要依赖
首先确保你安装了pandas和openpyxl(pandas保存XLSX需要这个引擎),在终端运行:
pip install pandas openpyxl
步骤2:修改你的代码
下面是调整后的完整代码,我加了注释说明改动点:
from oauth2client.service_account import ServiceAccountCredentials import gsheets import pandas as pd # 新增:导入pandas库 pdkey = "keypd.json" url = f"https://docs.google.com/spreadsheets/d/1MCkqb_123123123123asdasdada/edit#gid=0" SCOPE = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"] CREDS = ServiceAccountCredentials.from_json_keyfile_name(pdkey, SCOPE) sheets = gsheets.Sheets(CREDS) sheet = sheets.get(url) # 新增:把工作表数据转换成pandas DataFrame df = sheet[0].to_frame() # 新增:导出为XLSX格式(index=False是去掉自动生成的行索引) df.to_excel("/root/xlsx/SAMPLE.xlsx", index=False, engine='openpyxl') # 保留原有的CSV导出(如果需要的话) sheet[0].to_csv("/root/xlsx/SAMPLE.csv")
关键说明
sheet[0].to_frame():把gsheets的工作表对象转换成DataFrame,这是衔接的关键一步。df.to_excel():pandas的这个方法专门用来导出XLSX,engine='openpyxl'明确指定使用的引擎(避免环境差异导致的问题)。- 你可以同时保留CSV和XLSX的导出代码,两者互不影响。
内容的提问来源于stack exchange,提问作者rodskies
相关产品推荐
相关产品推荐

