3
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ローカルのCSVをGoogleSpreadSheetに上げる

Last updated at Posted at 2017-07-21

ローカルにあるCSVのデータをGoogleSpreadSheetに
そっくりあげたかったので、そのためのスクリプトを作った。

以下、導入の簡単な説明とサンプルのスクリプト

GoogleSheetsAPIをONにする

ここを参考に
https://developers.google.com/sheets/api/quickstart/python#step_1_turn_on_the_api_name

GoogleClientLibraryをインストールする

ここを参考に
https://developers.google.com/sheets/api/quickstart/python#step_2_install_the_google_client_library

認証用の関数を作る

ここのget_credentialsをそのまま
https://developers.google.com/sheets/api/quickstart/python#step_3_set_up_the_sample

ただしSCOPEに関しては、編集を行うので次に変更https://www.googleapis.com/auth/drive

サンプル

  • CSVファイルを取得して行ごとに要素にして、リストにまとめる関数
def csv2rows(csv_name):
    df = pd.read_csv(csv_name, index_col=False)
    rows = []
    for index, row in df.iterrows():
        values = []
        for c in row:
            values.append({'userEnteredValue': {'stringValue': str(c)}})
        rows.append({'values': values})
    return rows
  • csvファイルを取得して、スプレッドシートにあげる
sheet_index = 1
requests = []

rows =  csv2rows('aaa.csv', header=None)
sheet_title = 'aaa'
sheet_id = sheet_index
requests.append(
    { # シートの作成
      'addSheet': {
        'properties': {
          'title': sheet_title,
          'index': 0,
          'sheetId': sheet_id
        }
      }
    }
)
requests.append(
    { # 作成したシートを取得したcsvの内容でupdate
        'updateCells': {
          'start': {
            'sheetId': sheet_id,
            'rowIndex': 0,
            'columnIndex': 0
          },
          'rows': rows,
          'fields': 'userEnteredValue'
        }
    }
)

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)

spreadsheet_id = '${任意のSpreadSheetId}'

batch_update_spreadsheet_request_body = {
  'requests': requests
}

# リクエストの実行
result = service.spreadsheets() \
                          .batchUpdate(spreadsheetId=spreadsheet_id, body=batch_update_spreadsheet_request_body) \
                          .execute()
3
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?