1、背景
- 作為一個sql boy 其實基本上大部分的數據均在數據產品做自動化更新了,但是有某些數據因為沒有落庫(需要excel各種公式計算),或者是給ceo出日報等,需要比較靈活沒有辦法放到數據產品上提供服務,這個時候需要把數據放到excel上給到需求方。。。久而久之這樣確實是很浪費時間,所以最好的方式是python自動處理計算邏輯,自動寫入google sheet(云文檔),需求方打開即閱。
2、申請google sheet API
2.1 進入Google cloud控制臺
2.2 創建新項目
[圖片上傳失敗...(image-8b5d7-1663489452044)]
[圖片上傳失敗...(image-26cad7-1663489452044)]
[圖片上傳失敗...(image-b19cd1-1663489452044)]
2.3 啟用API和服務
[圖片上傳失敗...(image-7fbe95-1663489452044)]
[圖片上傳失敗...(image-12a234-1663489452044)]
[圖片上傳失敗...(image-b32dd7-1663489452044)]
2.4 創建憑證
[圖片上傳失敗...(image-d074d3-1663489452044)]
[圖片上傳失敗...(image-fb4c34-1663489452044)]
[圖片上傳失敗...(image-f2c67d-1663489452044)]
2.5 獲取私鑰文件
[圖片上傳失敗...(image-619a93-1663489452044)]
[圖片上傳失敗...(image-516b96-1663489452044)]
[圖片上傳失敗...(image-ec7b8c-1663489452044)]
[圖片上傳失敗...(image-9863a1-1663489452044)]
3、創建Google sheet
[圖片上傳失敗...(image-5cd94a-1663489452044)]
3.1 共享編輯權限
- 打開上一步操作獲取的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
# 關聯參數
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 數據操作
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名
# 數據寫入
wks.set_dataframe(df,(1,1),nan='', fit = True)
# 讀取對應sheet的數據
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