You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

已完成Google Drive认证,如何设置file_path以将DataFrame追加至云端Excel文件工作表?

解决Google Drive上Excel文件的Pandas追加写入问题

直接用本地文件路径file_path是行不通的,因为Pandas的ExcelWriter只能操作本地文件系统里的文件,而Google Drive上的文件存储在云端,没有直接的本地路径可以引用。我们需要先把云端的Excel文件下载到本地临时目录,修改完成后再上传回Google Drive覆盖原文件。

下面是具体的实现步骤,假设你已经完成了Google Drive的身份验证流程(不管是OAuth2还是服务账号认证):

方法1:使用官方Google Drive API(google-api-python-client)

步骤1:下载云端Excel文件到本地临时文件

首先需要获取目标文件的ID——你可以在Google Drive文件的预览URL里找到,比如https://drive.google.com/file/d/ABC123XYZ/view中的ABC123XYZ就是文件ID。

import io
import os
import tempfile
import pandas as pd
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload

# 假设你已经通过认证得到了drive_service对象(比如googleapiclient.discovery.build后的实例)
file_id = "替换成你的Google Drive文件ID"

# 创建一个临时文件来存储下载的Excel
temp_file = tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False)

# 执行下载
request = drive_service.files().get_media(fileId=file_id)
downloader = MediaIoBaseDownload(temp_file, request)
done = False
while not done:
    status, done = downloader.next_chunk()
temp_file.close()

步骤2:用你的代码追加数据到临时文件

这部分就是你原本的代码,只是把file_path换成临时文件的路径:

with pd.ExcelWriter(temp_file.name, mode='a', engine="openpyxl", if_sheet_exists="overlay") as writer:
    example_dataframe.to_excel(writer, sheet_name='sheet1', header=False, index=False, startrow=8, startcol=2)

步骤3:上传修改后的文件回Google Drive

覆盖原文件完成更新:

# 准备上传的媒体对象
media = MediaFileUpload(temp_file.name, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

# 更新云端文件
drive_service.files().update(
    fileId=file_id,
    media_body=media
).execute()

# 清理临时文件
os.unlink(temp_file.name)

方法2:使用PyDrive2(更简洁的封装库)

如果你觉得官方API代码有点繁琐,可以用PyDrive2库来简化流程:

import os
import tempfile
import pandas as pd
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

# 加载已完成的认证(比如从本地凭证文件加载)
gauth = GoogleAuth()
gauth.LoadCredentialsFile("your_credentials_file.txt")  # 替换成你的凭证文件路径
gauth.Authorize()
drive = GoogleDrive(gauth)

file_id = "替换成你的Google Drive文件ID"
# 获取云端文件对象
drive_file = drive.CreateFile({'id': file_id})

# 下载到临时文件
temp_file = tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False)
drive_file.GetContentFile(temp_file.name)

# 追加数据
with pd.ExcelWriter(temp_file.name, mode='a', engine="openpyxl", if_sheet_exists="overlay") as writer:
    example_dataframe.to_excel(writer, sheet_name='sheet1', header=False, index=False, startrow=8, startcol=2)

# 上传回云端覆盖原文件
drive_file.SetContentFile(temp_file.name)
drive_file.Upload()

# 清理临时文件
os.unlink(temp_file.name)

注意事项

  • 确保目标文件是.xlsx格式,openpyxl引擎不支持旧版的.xls文件
  • 临时文件会自动创建,用完一定要删除,避免占用本地存储空间
  • 如果是多人协作的文件,操作时要注意并发问题(比如别人同时修改文件可能导致冲突)

内容的提问来源于stack exchange,提问作者Xubo

火山引擎 最新活动