如何修改Python代码将CSV数据写入指定Google Sheet的Sheet3
解决方案:将CSV数据导入指定Google表格的Sheet3
你的现有代码是通过PyDrive将CSV作为新文件上传到Google Drive,但要更新已存在的Google表格的Sheet3,需要使用Google Sheets API直接操作表格内容。以下是修改后的完整实现:
步骤1:安装依赖
先确保安装所需库:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib pandas
步骤2:修改后的代码
import os import glob import pandas as pd from google.oauth2.service_account import Credentials from googleapiclient.discovery import build # 配置认证(使用服务账号密钥文件,需提前在Google Cloud控制台创建) SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SERVICE_ACCOUNT_FILE = 'path/to/your/service-account-key.json' # 替换为你的密钥文件路径 creds = Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # 指定目标Google表格ID和Sheet名称 SPREADSHEET_ID = 'YOUR_SPREADSHEET_ID' # 替换为你的表格ID(URL中d/和/edit之间的字符串) SHEET_NAME = 'Sheet3' # 获取最新的CSV文件 os.chdir(r'DIRECTORY OF CSV') list_of_files = glob.glob('*.csv') latest_file = max(list_of_files, key=os.path.getctime) print(f"正在处理文件: {latest_file}") # 读取CSV数据(包含表头) df = pd.read_csv(latest_file) data = [df.columns.tolist()] + df.values.tolist() # 连接Google Sheets API并更新Sheet3 service = build('sheets', 'v4', credentials=creds) sheet = service.spreadsheets() # 清除Sheet3原有内容(可选,按需调整清除范围) clear_request = sheet.values().clear( spreadsheetId=SPREADSHEET_ID, range=f'{SHEET_NAME}!A:Z' ) clear_request.execute() # 写入新数据 update_request = sheet.values().update( spreadsheetId=SPREADSHEET_ID, range=f'{SHEET_NAME}!A1', valueInputOption='USER_ENTERED', body={'values': data} ) update_response = update_request.execute() print(f"数据更新完成,共写入 {update_response.get('updatedRows')} 行")
关键说明
- 认证配置:需在Google Cloud控制台启用Google Sheets API,创建服务账号并下载密钥文件,同时将服务账号邮箱添加到目标表格的共享列表,赋予编辑权限。
- 清除操作:代码中默认清除Sheet3的A-Z列,若需保留特定区域数据,可修改
range参数(比如{SHEET_NAME}!A1:Z100)。 - 数据格式:使用
USER_ENTERED参数,Google Sheets会自动识别数字、日期等格式,和手动输入效果一致。
关于PyDrive的补充说明
PyDrive仅适用于Drive文件的上传/管理,无法直接编辑Google表格的单元格内容,因此更推荐使用上述Sheets API方案实现精准的Sheet更新需求。
内容的提问来源于stack exchange,提问作者Johnny Quest
相关产品推荐
相关产品推荐

