プログラミング

oauth2clientとgspreadを使ってGoogleスプレッドシートをPythonで操作する

参考:
[get_title https://qiita.com/AAkira/items/22719cbbd41b26dbd0d1]
[get_title https://github.com/burnash/gspread]

スプレッドシートのID と ダウンロードしたJsonファイルのPATH を入力して、スクリプトを実行してみてください。

import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials

def main():
    scope = ['https://spreadsheets.google.com/feeds']

    # スプレッドシートのID
    doc_id = ''

    # ダウンロードしたJsonファイルのPATH
    path = os.path.expanduser("/mnt/c/_downloads/yuis Project 01-8c4909bd59b7.json")

    credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope)
    client = gspread.authorize(credentials)
    gfile   = client.open_by_key(doc_id)
    worksheet  = gfile.sheet1
    records = worksheet.get_all_values()

    # 単体のセルをアップデートする

    worksheet.update_acell('B1', 'Bingo!')

    # 範囲のセルをアップデートする

    cell_list = worksheet.range('A1:C7')

    for cell in cell_list:
        cell.value = 'O_o'

    worksheet.update_cells(cell_list)


    # 全てのレコードを順番に出力
    for record in records:
        print(record)

    # レコードからセルを順番に出力
    for record in records:
        print(record[1])
        print(record[2])
        print(record[3])
        print('===')

    # セルの値を取得
    val = worksheet.acell('B1').value
    print(val)

    # or
    val = worksheet.cell(1, 2).value
    print(val)

    # セルの式を確認したい
    cell = worksheet.acell('B1') # or .cell(1, 2)
    print(cell.input_value)



if __name__ == '__main__':
    main()


コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です