ピボットテーブルを作る
シート上の行をピボットテーブルに集計し、Excel で開いて更新できる形にするとき、レポートを読み戻すとき、行が変わったあとにレポートを最新にするときの手順です。ピボットの全オプションは ピボットのフィールド設定 に、呼び出しの一覧は WASM API と Python API にあります。
シートの範囲からキャッシュを作る
ピボットはシートではなくピボットキャッシュから読みます。setWorksheetSource はキャッシュの元になる範囲(シート上の範囲か定義名)を指定し、refresh() は Excel の「更新」と同じ方法でその範囲を読み込みます。見出し行がキャッシュのフィールドになり、その下の各行がレコードになります。
import createFormulon from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
console.log(cache.getRecordCount()) // 4
console.log(cache.listFields().map((f) => f.name).join()) // Region,Product,Sales
console.log(cache.getRecordValue(1, 'Sales').value) // 30
const source = cache.getWorksheetSource()
console.log(wb.sheet(source.range.sheet).name, JSON.stringify(source.range.rect)) // Sheet1 {"firstRow":0,"firstCol":0,"lastRow":4,"lastCol":2}
cache.setWorksheetSource(source)
} finally {
wb.dispose()
}from formulon import PivotWorksheetSourceInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
print(cache.get_record_count()) # 4
print(",".join(f.name for f in cache.list_fields())) # Region,Product,Sales
print(cache.get_record_value(1, "Sales").value) # 30.0
source = cache.get_worksheet_source()
print(wb.sheet(source.range.sheet).name, source.range.rect) # Sheet1 CellRect(first_row=0, first_col=0, last_row=4, last_col=2)
cache.set_worksheet_source(source)getWorksheetSource() は、シートはインデックス(range.sheet)、セル範囲は CellRect で返します。返されたレコードは、そのまま setWorksheetSource に渡せます。定義名で指定したソースを読み戻すと、name が設定され、range は null になります。キャッシュにソースがない場合やソースを解決できない場合、refresh() は StatusCode.PreconditionFailed で失敗します。
ピボットを作ってフィールドを配置する
ws.addPivot は anchor を起点にピボットを作ります。作成直後のピボットにはキャッシュのフィールドごとに 1 つのフィールドがあり、どれも軸に置かれていません。setFieldAxis(field, axis) はフィールドを行、列、ページ(フィルター)領域、値のいずれかに置き、null を渡すと軸から外します。フィールドはキャッシュのフィールド名か位置で指定します。行または列に置いたフィールドはその軸の並びの末尾に加わり、getRowFieldOrder() と getColumnFieldOrder() はその並びをキャッシュ内の位置で返します。
import createFormulon, { PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Product', PivotAxis.Column)
pivot.setFieldAxis('Sales', PivotAxis.Value)
console.log(JSON.stringify(pivot.getRowFieldOrder())) // [0]
console.log(JSON.stringify(pivot.getColumnFieldOrder())) // [1]
console.log(pivot.getField('Sales').axis === PivotAxis.Value) // true
} finally {
wb.dispose()
}from formulon import PivotAxis, PivotInput, PivotWorksheetSourceInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Product", PivotAxis.COLUMN)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
print(pivot.get_row_field_order()) # [0]
print(pivot.get_column_field_order()) # [1]
print(pivot.get_field("Sales").axis == PivotAxis.VALUE) # True値の軸に置いたフィールドは、データフィールドで集計するまで何も表示しません。データフィールドは次の手順で追加します。
データフィールドを追加してレポートを読む
addDataField は 1 つのフィールドの集計を追加します。name を省くと、プロファイルの言い回しで名前が付きます。英語プロファイルなら Sum of Sales です。エンジンはレポートを起点からシートのセルに書き込むので、ほかの範囲と同じように getValues で読めます。setRowFieldOrder と setColumnFieldOrder はその軸に載るフィールドをまとめて置き換えるので、2 つのリストを入れ替えるとレポートの縦横が入れ替わります。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Product', PivotAxis.Column)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(pivot.listDataFields()[0].name) // Sum of Sales
let report = ws.getValues('E1:H5')
console.log(JSON.stringify(report[1])) // ["Row Labels","Gadget","Widget","Grand Total"]
console.log(JSON.stringify(report[2])) // ["East",5,10,15]
console.log(JSON.stringify(report[4])) // ["Grand Total",35,30,65]
pivot.setRowFieldOrder(['Product'])
pivot.setColumnFieldOrder(['Region'])
report = ws.getValues('E1:H5')
console.log(JSON.stringify(report[1])) // ["Row Labels","East","West","Grand Total"]
console.log(JSON.stringify(report[2])) // ["Gadget",5,30,35]
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Product", PivotAxis.COLUMN)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
print(pivot.list_data_fields()[0].name) # Sum of Sales
report = ws["E1:H5"]
print(report[1]) # ['Row Labels', 'Gadget', 'Widget', 'Grand Total']
print(report[2]) # ['East', 5.0, 10.0, 15.0]
print(report[4]) # ['Grand Total', 35.0, 30.0, 65.0]
pivot.set_row_field_order(["Product"])
pivot.set_column_field_order(["Region"])
report = ws["E1:H5"]
print(report[1]) # ['Row Labels', 'East', 'West', 'Grand Total']
print(report[2]) # ['Gadget', 5.0, 30.0, 35.0]PivotAggregation には Count、Average、Max、Min など Excel の集計方法がそろっています。データフィールドの showAs で計算の種類も選べます。行の軸にフィールドを 2 つ置いたときは、リストの順が入れ子の順になります。先頭が最も外側です。
元データが変わったら更新する
キャッシュはレコードのコピーを独自に持っているので、元のセルを編集してもそれだけではピボットは変わりません。cache.refresh() は Excel の「更新」と同じく元の範囲を読み直し、そのキャッシュを使うすべてのピボットに新しい数値が表示されます。ピボットを参照する GETPIVOTDATA の数式は、次の計算で新しい値を返します。範囲の下に追加した行は範囲の外です。setWorksheetSource で範囲を広げるか、データとともに広がる定義名やテーブルを元にしてください。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
ws.setFormula('H1', '=GETPIVOTDATA("Sales",E1,"Region","East")')
ws.setValue('C2', 100)
console.log(ws.getValue('F2'), ws.getValue('H1')) // 15 15
cache.refresh()
console.log(ws.getValue('F2'), ws.getValue('H1')) // 105 105
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
ws.set_formula("H1", '=GETPIVOTDATA("Sales",E1,"Region","East")')
ws["C2"] = 100
print(ws["F2"], ws["H1"]) # 15.0 15.0
cache.refresh()
print(ws["F2"], ws["H1"]) # 105.0 105.0保存して開き直す
save() はピボットの定義、キャッシュ、投影したセルを書き出します。Excel ではレポートが表示された状態でファイルが開き、同じ元の範囲から更新されます。読み込んだワークブックでは、ws.listPivots() や ws.pivot(name) でピボットが得られ、そのキャッシュを再び更新できます。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
let bytes
try {
const ws = wb.sheet(0)
ws.setValues('A1', [
['Region', 'Product', 'Sales'],
['East', 'Widget', 10],
['West', 'Gadget', 30],
['East', 'Gadget', 5],
['West', 'Widget', 20],
])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'A1:C5', sheet: 'Sheet1' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
bytes = wb.save()
} finally {
wb.dispose()
}
const back = formulon.Workbook.load(bytes)
try {
const ws = back.sheet(0)
const pivot = ws.pivot('SalesByRegion')
console.log(pivot.listDataFields()[0].name) // Sum of Sales
ws.setValue('C3', 50)
pivot.cache().refresh()
console.log(JSON.stringify(ws.getValues('E4:F4'))) // [["Grand Total",85]]
} finally {
back.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotWorksheetSourceInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values("A1", [
["Region", "Product", "Sales"],
["East", "Widget", 10],
["West", "Gadget", 30],
["East", "Gadget", 5],
["West", "Widget", 20],
])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range="A1:C5", sheet="Sheet1"))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
wb.save("pivot.xlsx")
with Workbook.load("pivot.xlsx") as back:
ws = back[0]
pivot = ws.pivot("SalesByRegion")
print(pivot.list_data_fields()[0].name) # Sum of Sales
ws["C3"] = 50
pivot.cache().refresh()
print(ws["E4:F4"]) # [['Grand Total', 85.0]]レコードからキャッシュを作る
データベースの行のように、どのシートにもないデータをキャッシュに持たせることもできます。列ごとに addField でフィールドを追加し、行ごとに addRecord と setRecordValue でレコードを追加します。setRecordValue のフィールドは位置でも名前でも指定できます。レコードを変更すると、そのキャッシュを使うピボットはすべて保留状態(isProjectionPending())になり、pivot.project() でレポートを書き込み直します。このようなピボットを保存する場合も、Excel が更新に使うワークシートソースがキャッシュに必要です。ソースがないと save() は失敗します。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'A1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(JSON.stringify(ws.getValues('A2:B3'))) // [["East",15],["West",50]]
cache.setRecordValue(0, 'Sales', 100)
console.log(pivot.isProjectionPending(), ws.getValue('B2')) // true 15
pivot.project()
console.log(pivot.isProjectionPending(), ws.getValue('B2')) // false 105
} finally {
wb.dispose()
}from formulon import PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput, Workbook
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="A1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
print(ws["A2:B3"]) # [['East', 15.0], ['West', 50.0]]
cache.set_record_value(0, "Sales", 100)
print(pivot.is_projection_pending(), ws["B2"]) # True 15.0
pivot.project()
print(pivot.is_projection_pending(), ws["B2"]) # False 105.0描画用にレイアウトを読む
pivot.getLayout() はレポートをセルのリストで返します。各セルはシート上の位置、値、kind(PivotCellKind:見出し、行ラベル、列ラベル、データ、小計、総計、空白)、アウトラインの depth、フィールド名、表示形式、expansion(PivotCellExpansion)を持ちます。expansion はアイテムのラベルにある展開 / 折りたたみボタンの状態で、ボタンがなければ null です。ピボットを自前で描画するホストは、これを使ってラベルや合計の見た目を変え、ボタンを描きます。getLayout() はキャッシュのレコードからレポートを計算するだけで、シートには何も書き込みません。
import createFormulon, { PivotAggregation, PivotAxis, PivotCellKind } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'E1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const layout = pivot.getLayout()
console.log(JSON.stringify(layout.range)) // {"firstRow":0,"firstCol":4,"lastRow":3,"lastCol":5}
const labels = layout.cells.filter((c) => c.kind === PivotCellKind.RowLabel)
console.log(labels.map((c) => `${c.value}@${c.row},${c.col}`).join(' ')) // East@1,4 West@2,4
const data = layout.cells.filter((c) => c.kind === PivotCellKind.Data)
console.log(data.map((c) => c.value).join()) // 15,50
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotCellKind,
PivotDataFieldInput,
PivotInput,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="E1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
layout = pivot.get_layout()
r = layout.range
print(r.first_row, r.first_col, r.last_row, r.last_col) # 0 4 3 5
labels = [c for c in layout.cells if c.kind == PivotCellKind.ROW_LABEL]
print(" ".join(f"{c.value}@{c.row},{c.col}" for c in labels)) # East@1,4 West@2,4
data = [c for c in layout.cells if c.kind == PivotCellKind.DATA]
print([c.value for c in data]) # [15.0, 50.0]行フィールド、列フィールド、集計方法を切り替えて、getLayout() が返すセルを確認できます。
ピボットテーブル
元の表と同じ行をピボットキャッシュに入れ、行・列フィールドと集計方法を切り替えるたびにピボットを組み直して getLayout() の結果を表示します。
本物の Formulon エンジン (WASM) がこのページ内で動作します。データは送信されません。
並べ替え、名前の変更、値の取得
updateField(field, patch) はフィールドの並べ替え順、小計、表示形式などのプロパティを変更し、レポートはその場で投影し直されます。rename はピボットの名前を変更します。GETPIVOTDATA はフィールドとアイテムを指定してレポートから数値を読みます。データフィールドは元の名前(Sales)でも、データフィールド自身の名前(Sum of Sales)でも指定できます。
import createFormulon, { PivotAggregation, PivotAxis, PivotSortOrder } from '@libraz/formulon'
const formulon = await createFormulon()
const wb = formulon.Workbook.createDefault()
try {
const ws = wb.sheet(0)
const cache = wb.addPivotCache()
for (const name of ['Region', 'Product', 'Sales']) cache.addField(name)
for (const row of [['East', 'Widget', 10], ['West', 'Gadget', 30], ['East', 'Gadget', 5], ['West', 'Widget', 20]]) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesByRegion', cacheId: cache.cacheId, anchor: 'A1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.setFieldAxis('Sales', PivotAxis.Value)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
pivot.updateField('Region', { sortOrder: PivotSortOrder.Descending })
pivot.rename('Sales by region')
console.log(JSON.stringify(ws.getValues('A2:B3'))) // [["West",50],["East",15]]
console.log(ws.listPivots().map((p) => p.name).join()) // Sales by region
ws.setFormula('E1', '=GETPIVOTDATA("Sales",A1,"Region","East")')
ws.setFormula('E2', '=GETPIVOTDATA("Sum of Sales",A1,"Region","West")')
console.log(ws.getValue('E1'), ws.getValue('E2')) // 15 50
} finally {
wb.dispose()
}from formulon import (
PivotAggregation,
PivotAxis,
PivotDataFieldInput,
PivotInput,
PivotSortOrder,
Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
cache = wb.add_pivot_cache()
for name in ("Region", "Product", "Sales"):
cache.add_field(name)
for row in [["East", "Widget", 10], ["West", "Gadget", 30], ["East", "Gadget", 5], ["West", "Widget", 20]]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name="SalesByRegion", cache_id=cache.cache_id, anchor="A1"))
pivot.set_field_axis("Region", PivotAxis.ROW)
pivot.set_field_axis("Sales", PivotAxis.VALUE)
pivot.add_data_field(PivotDataFieldInput(field_index="Sales", aggregation=PivotAggregation.SUM))
pivot.update_field("Region", sort_order=PivotSortOrder.DESCENDING)
pivot.rename("Sales by region")
print(ws["A2:B3"]) # [['West', 50.0], ['East', 15.0]]
print(",".join(p.name for p in ws.list_pivots())) # Sales by region
ws.set_formula("E1", '=GETPIVOTDATA("Sales",A1,"Region","East")')
ws.set_formula("E2", '=GETPIVOTDATA("Sum of Sales",A1,"Region","West")')
print(ws["E1"], ws["E2"]) # 15.0 50.0フィルター、小計、日付のグループ化、計算フィールド、レポートのレイアウトは ピボットのフィールド設定 を参照してください。