Google Sheets Python API

1、背景

  • 作為一個sql boy 其實基本上大部分的數(shù)據(jù)均在數(shù)據(jù)產(chǎn)品做自動化更新了,但是有某些數(shù)據(jù)因為沒有落庫(需要excel各種公式計算),或者是給ceo出日報等,需要比較靈活沒有辦法放到數(shù)據(jù)產(chǎn)品上提供服務,這個時候需要把數(shù)據(jù)放到excel上給到需求方。。。久而久之這樣確實是很浪費時間,所以最好的方式是python自動處理計算邏輯,自動寫入google sheet(云文檔),需求方打開即閱。

2、申請google sheet API

2.1 進入Google cloud控制臺

2.2 創(chuàng)建新項目

[圖片上傳失敗...(image-8b5d7-1663489452044)]

[圖片上傳失敗...(image-26cad7-1663489452044)]

[圖片上傳失敗...(image-b19cd1-1663489452044)]

2.3 啟用API和服務

[圖片上傳失敗...(image-7fbe95-1663489452044)]

[圖片上傳失敗...(image-12a234-1663489452044)]

[圖片上傳失敗...(image-b32dd7-1663489452044)]

2.4 創(chuàng)建憑證

[圖片上傳失敗...(image-d074d3-1663489452044)]

[圖片上傳失敗...(image-fb4c34-1663489452044)]

[圖片上傳失敗...(image-f2c67d-1663489452044)]

2.5 獲取私鑰文件

[圖片上傳失敗...(image-619a93-1663489452044)]

[圖片上傳失敗...(image-516b96-1663489452044)]

[圖片上傳失敗...(image-ec7b8c-1663489452044)]

[圖片上傳失敗...(image-9863a1-1663489452044)]

3、創(chuàng)建Google sheet

[圖片上傳失敗...(image-5cd94a-1663489452044)]

3.1 共享編輯權(quán)限

  • 打開上一步操作獲取的json文件拿郵箱地址
"client_email": "test-api@plucky-haven-318207.iam.gserviceaccount.com"
# test-api@plucky-haven-318207.iam.gserviceaccount.com

[圖片上傳失敗...(image-1ef58b-1663489452044)]

4、python操作

4.1 模塊安裝

import pygsheets # pip install pygsheets 
import pandas as pd
from pyhive import presto # python連接presto

# 關(guān)聯(lián)參數(shù)
conn = presto.connect(protocol='https', host='', port=,username="", password = '')

# 獲取dataframe
df = pd.read_sql_query(
'''
select * from xxx 
'''
, conn)

# df = pd.read_sql_query(open('/data/jupyter/Data.sql','r').read() , conn)

4.2 數(shù)據(jù)操作

client = pygsheets.authorize(service_file = "plucky-haven-318207-0eb060f3f328.json")

# 獲取Google sheet
sh = client.open('test') # test為gs的表名
# 指定對應的sheet
wks = sh.worksheet_by_title('title1') # title1 為對應sheet名

# 數(shù)據(jù)寫入
 wks.set_dataframe(df,(1,1),nan='', fit = True)

# 讀取對應sheet的數(shù)據(jù)
df = pd.DataFrame(wks.get_all_records())

延伸閱讀

pygsheet官方文檔:https://pygsheets.readthedocs.io/en/stable/

pygsheets github:https://github.com/nithinmurali/pygsheets

Python 串接 GoogleSheet 新增、讀取、更新和刪除:https://www.maxlist.xyz/2018/09/25/python_googlesheet_crud/#%E4%BA%8C_Python_%E6%96%B0%E5%A2%9E_GoogleSheet_%E8%B3%87%E6%96%99

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容