LoginSignup
0
0

More than 3 years have passed since last update.

Google Spreadsheet API v4 Pivot Table (ピボットテーブル)のサンプルコードをコピペしても動かないし、エラーも吐かない件

Last updated at Posted at 2020-02-21

Pivot Tables

下の方にあるコードサンプル
Pivot_Tables_ _ _Sheets_API_ _ _Google_Developers.png

問題

適当なデータを用意して、適当なsource範囲なりで設定して実行すると

Success - #<Google::Apis::SheetsV4::BatchUpdateSpreadsheetResponse:0x00005567c9a9e490

などと返ってくるが、実際にはPivotテーブルが作られていない。

原因

Pivotテーブルを作るにはbatchUpdateupdateCellsを使って更新するが、パラメータのネストが深い。そしてサンプルコードが間違っている。

UpdateCellsRequest

  • rows <= ここが深い
  • fields
  • start / range (union fieldという事で、どちらかいずれか)

rows

まず、配列だ

rows: [RowData, RowData, RowData ...]

RowData

valuesが配列

values: [CellData, CellData, CellData ...]

CellData

pivotTable要素がある

総合すると

requests = []

requests.push(
  {
    update_cells: {
      # 配列
      rows: [
        {
          # 配列
          values: [
            {
              # PivotTableの内容
              pivot_table: {
                source: {
                  ...
                  ...
                },
                rows: [
                  ...
                  ...
                ],
                values: [
                  ...
                  ...
                ]
              }
            }
          ]
        }
      ],
      # pivotTableを指定
      # https://developers.google.com/slides/how-tos/field-masks?utm_campaign=gsuite_series_slidesapi_041317&utm_source=gdev&utm_medium=yt-desc#updating_with_a_field_mask
      fields: "pivotTable",
      start: { 
        ...
      }
    }
  }
)

request_object = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new
request_object.requests = requests

# request_objectを {requests: requests} で渡すとなぜかエラー
# ArgumentError: unknown keyword: requests
response = GoogleApi.sheet_service.batch_update_spreadsheet(
  your_spreadsheet_id,
  request_object
)

サンプルコードはrowsが配列になっていないので(invalid)、Pivotテーブルは作られない(が、エラーも出ない)。

Method: spreadsheets.batchUpdate

Each request is validated before being applied. If any request is not valid then the entire request will fail and nothing will be applied.

1個でも変なのがあれば、全部取り止めって書いてあるように読めるが...

0
0
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
0
0