エクセルファイルを pandas の dataframe に読み込ませて spreadsheets に貼り付ける方法をまとめてみました。
事前準備
python から spreadsheets を操作する方法とpandas で エクセルファイルを操作する方法は以下にまとめてます。
a1026302.hatenablog.com
a1026302.hatenablog.com
python
gspread-dataframe インストール
pandas の Dataframe からスプレッドシートにデータを反映するには gspread-dataframe というライブラリをインストールします。
$ pip install gspread-dataframe
エクセルファイル操作
エクセルファイルを pandas の dataframe に読み込ませます。
import pandas as pd # エクセルファイル読み込み(シートの一枚目) df = pd.ExcelFile('./sample.xlsx', engine='openpyxl') input_sheet_name = df.sheet_names sheet_df = df.parse(input_sheet_name[0])
スプレッドシート操作
pandas の dataframe の情報をspreadsheets に貼り付けます。
import gspread from oauth2client.service_account import ServiceAccountCredentials scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] #jsonファイルを指定 credentials = ServiceAccountCredentials.from_json_keyfile_name( '~/sample.json', scope ) # 認証 gc = gspread.authorize(credentials)
スプレッドシートにコピー
スプレッドシートにコピーするコードは以下のような感じです。
import pandas as pd import gspread from gspread_dataframe import get_as_dataframe, set_with_dataframe import gspread_dataframe as gs_df # 'sample'一つ目のワークシート worksheet = gc.open('pythonコピー練習01').get_worksheet(0) # write gs_df.set_with_dataframe(worksheet, sheet_df)