簡體   English   中英

每次運行 python 腳本時,如何使用新結果更新 google 表?

[英]How to update google sheet with new outcome every time python script runs?

我有一個 python 腳本,每次運行它都會返回一個新值。 然后我需要將這些值添加到 google 表中。 所以每天腳本的結果都會被添加到一個新行中。 我嘗試使用“pygsheet”庫,但我無法處理每天添加到新行的操作。 如何將數據添加到最后一個空行?

首先,獲取電子表格中的所有值。 您需要將include_tailing_empty_rowsinclude_tailing_empty指定為False ,以便空行不會包含在計數中

new_row = ['firstname', 'lastname', 'Email', 'Number']
worksheet = gc.open('Sign Up').sheet1
cells = worksheet.get_all_values(include_tailing_empty_rows=False, include_tailing_empty=False, returnas='matrix')
last_row = len(cells)
worksheet = worksheet.insert_rows(last_row, number=1, values= new_row)

insert_rows將“new_row”列表添加到緊跟在“last_row”之后的位置。

您可以在此處查看worksheet其他屬性https://pygsheets.readthedocs.io/en/stable/worksheet.html

使用 pygsheets 有多種方法可以實現這一點。 insert_rows可以在insert_rows中實現。

wks.insert_rows(wks.rows, values=[daily_value], inherit=True) # here wks is the worksheet object

如果您不想添加新行或想在非最后一行中添加值,您可以使用append_table ,假設這是工作表中唯一的數據。 在這里,您必須確保您的工作表有足夠的行來適應新值。

wks.append_table(values=[daily_value])

以下代碼片段將向最后一個非空行添加數據。

#open the google spreadsheet 
sh = gc.open('name of the google sheet')

#select the first sheet 
wks = sh[0]

#retrieve all rows of the worksheet
cells = wks.get_all_values(include_tailing_empty_rows=False, include_tailing_empty=False, returnas='matrix')

#extract all non empty rows
nonEmptyRows = []
for i in cells:
    if i != []:
        nonEmptyRows.append(i)

#calculating the length 
countOfnonEmptyRows = len(nonEmptyRows)
type(countOfnonEmptyRows)

#defining the data
ls = ['G', 'H', 'I']


#inserting data 
wks.insert_rows(countOfnonEmptyRows, values=ls, inherit=True) # here wks is the worksheet object
# Connect with Google Sheet
# pip install pygsheets 
# append data on google sheet with existing data Final working
import pygsheets
import pandas as pd

#Change Path : excel file path
df=pd.read_excel(r"C:\Users\Ankur\Desktop\Google Sheet\CET Not Open.xlsx")
#Change Path : Your Key File Path Json file for Google Sheet API
path=r'C:\Users\Ankur\Desktop\Google Sheet\our-brand-301715-306ddc60d5ce.json'
gc = pygsheets.authorize(service_account_file=path)
# Change Sheet Name : PythonDB to your googlesheet name
sh=gc.open("PythonDB")
wk1=sh[0]
cells = wk1.get_all_values(include_tailing_empty_rows=None, include_tailing_empty=False, returnas='matrix')
last_row = len(cells)
if last_row>1:
    wk1.set_dataframe(df,(last_row+1,1))
    wk1.delete_rows(last_row+1)
else:
    wk1.set_dataframe(df,(1,1))
print("Data inserted successfully....")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM