You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将本地指定文件夹的Excel/CSV文件自动同步刷新至Google Drive/Google Sheet

本地Excel/CSV文件自动同步到Google Drive/Google Sheet方案

一、自动同步到Google Drive

1. Google Drive桌面客户端(零代码方案)

适合非技术用户,操作简单直接:

  • 安装Google Drive桌面客户端,登录你的Google账号。
  • 进入客户端设置,选择同步特定文件夹,指定本地存放更新文件的目标文件夹。
  • 后续只要将下载的Excel/CSV复制粘贴到这个本地文件夹,客户端会自动同步文件到Google Drive对应目录,云端文件会自动覆盖更新。

2. Python脚本(自定义同步逻辑)

适合需要定制同步规则的用户,需安装watchdog(监听文件变化)和pydrive(操作Google Drive)两个库:

  1. 安装依赖:
pip install watchdog pydrive
  1. 核心代码示例:
    先配置Google Drive OAuth2凭据(保存为client_secrets.json),再编写监听同步逻辑:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

# 替换为你的本地文件夹路径和Google Drive目标文件夹ID
LOCAL_FOLDER = "/path/to/your/local/folder"
DRIVE_FOLDER_ID = "your-google-drive-folder-id"

class FileSyncHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory:
            filename = os.path.basename(event.src_path)
            # 查找云端同名文件,存在则更新,不存在则上传
            file_list = drive.ListFile({'q': f"'{DRIVE_FOLDER_ID}' in parents and title='{filename}' and trashed=false"}).GetList()
            if file_list:
                drive_file = file_list[0]
                drive_file.SetContentFile(event.src_path)
                drive_file.Upload()
                print(f"已更新云端文件:{filename}")
            else:
                drive_file = drive.CreateFile({'title': filename, 'parents': [{'id': DRIVE_FOLDER_ID}]})
                drive_file.SetContentFile(event.src_path)
                drive_file.Upload()
                print(f"已上传新文件:{filename}")

if __name__ == "__main__":
    event_handler = FileSyncHandler()
    observer = Observer()
    observer.schedule(event_handler, LOCAL_FOLDER, recursive=False)
    observer.start()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

二、自动同步并刷新到Google Sheet

1. Drive同步+Sheet函数自动刷新

  • 先按上述方法将文件同步到Google Drive。
  • 打开目标Google Sheet,使用IMPORTDATA函数导入云端文件数据(替换为你的文件ID):
=IMPORTDATA("https://drive.google.com/uc?export=download&id=your-file-id")
  • 注意:需将Drive中文件权限设为任何人可查看(或共享给Sheet编辑账号),否则函数无法读取数据。
  • 定时自动刷新:用Google Apps Script设置触发规则:
    1. 在Sheet中打开扩展程序 > Apps脚本。
    2. 编写刷新函数:
function refreshImportData() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = sheet.getRange("A1"); // 替换为IMPORTDATA函数所在单元格
  var formula = range.getFormula();
  range.setFormula("");
  SpreadsheetApp.flush();
  range.setFormula(formula);
}
  1. 添加定时触发:在脚本编辑器中点击触发器 > 添加触发器,选择refreshImportData函数,设置触发频率(如每小时一次)。

2. Python脚本直接更新Google Sheet

适合实时刷新场景,使用gspread和pandas库:

  1. 安装依赖:
pip install gspread pandas oauth2client
  1. 核心代码示例:
    创建Google服务账号(下载credentials.json密钥文件),并将服务账号邮箱添加为Sheet编辑者,再编写监听更新逻辑:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd
import os

# 配置Google Sheet授权
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
client = gspread.authorize(creds)

# 替换为你的Google Sheet名称和本地文件夹路径
SHEET_NAME = "your-google-sheet-name"
LOCAL_FOLDER = "/path/to/your/local/folder"

class SheetSyncHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory and event.src_path.endswith(('.csv', '.xlsx')):
            filename = event.src_path
            # 读取本地文件数据
            if filename.endswith('.csv'):
                df = pd.read_csv(filename)
            else:
                df = pd.read_excel(filename)
            # 写入Google Sheet并覆盖原有数据
            sheet = client.open(SHEET_NAME).sheet1
            sheet.clear()
            sheet.update([df.columns.values.tolist()] + df.values.tolist())
            print(f"已更新Google Sheet:{filename}")

if __name__ == "__main__":
    event_handler = SheetSyncHandler()
    observer = Observer()
    observer.schedule(event_handler, LOCAL_FOLDER, recursive=False)
    observer.start()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:44:08