CSV 到 Google Sheets python

Joh*_*est 2 python google-sheets google-sheets-api

我有一个 CSV 文件,我想将其放入 Google Sheet 中的 Sheet3 中。我希望有人可以帮助我完成这段代码。我正在使用谷歌API。到目前为止,我已经将 csv 上传到谷歌驱动器。现在我想更改代码以更新sheet3中的特定google工作表而不是创建新工作表。您将在下面找到我用来创建包含 CSV 数据的新工作表的代码。

# Import Csv to Google Drive
import os
import glob

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()           
drive = GoogleDrive(gauth)  

 
# line used to change the directory
os.chdir(r'DIRECTORY OF CSV')

list_of_files = glob.glob('DIRECTORY OF CSV\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

upload_file_list = [latest_file]
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': 'THE GOOGLE ID'}]})
    # Read file and set it as the content of this instance.
    gfile.SetContentFile(upload_file)
    gfile.Upload() # Upload the file.
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 6

我相信您的目标如下。

  • 您想要将 CSV 数据放入 Google 电子表格的特定工作表中。
  • 您想使用 python 来实现这一点。
  • 您已经能够使用 Sheets API 获取电子表格中的值并将其放入电子表格中。

在这种情况下,下面的示例脚本怎么样?

示例脚本1:

当使用googleapis for python时,下面的示例脚本怎么样?

service = build("sheets", "v4", credentials=creds)  # Please use your script for authorization.
spreadsheet_id = "###"  # Please put your Spreadsheet ID.
sheet_name = "Sheet3"  # Please put the sheet ID of the sheet you want to use.
csv_file = "###"  # Please put the file path of the CSV file you want to use.

f = open(csv_file, "r")
values = [r for r in csv.reader(f)]
request = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=sheet_name, valueInputOption="USER_ENTERED", body={"values": values}).execute()
Run Code Online (Sandbox Code Playgroud)

示例脚本2:

当使用gspread for python时,下面的示例脚本怎么样?

import gspread
import csv

client = gspread.oauth(###) # Please use your script for authorization.
spreadsheet_id = "###"  # Please put your Spreadsheet ID.
sheet_name = "Sheet3"  # Please put the sheet ID of the sheet you want to use.
csv_file = "###"  # Please put the file path of the CSV file you want to use.

spreadsheet = client.open_by_key(spreadsheet_id)
worksheet = spreadsheet.worksheet(sheet_name)
f = open(csv_file, "r")
values = [r for r in csv.reader(f)]
worksheet.update(values)
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 对于这两个示例脚本,CSV 数据都是从本地 PC 上的 CSV 文件中检索的,然后将 CSV 数据转换为二维数组,并使用 Sheets API 将数组放入 Google Spreadsheet 的“Sheet3”中。在此示例脚本中,未使用 Drive API。

参考: