ピボットキャッシュ
ピボットキャッシュは、ピボットテーブルが集計する元データのフィールドとレコードを保持します。このページでは、キャッシュの読み取り元、更新による再構築、手で組み立てる方法を説明します。
キャッシュを更新する
cache.setWorksheetSource(source)(Python は set_worksheet_source(PivotWorksheetSourceInput(...)))は、キャッシュの読み込み元を次のいずれかで指定します。
range:'Sheet1!A1:C3'のようなシート名付きの A1 形式の範囲かSheetRect、またはシート名なしの範囲とsheetの組。name: このワークブックの定義名かテーブル。
ソースを設定しただけでは何も読み込みません。
cache.refresh() はソースからフィールドとレコードを作り直し、Excel の「更新」と同じように、そのキャッシュを使うすべてのピボットのレポートを書き直します。未計算のセルを先に計算し、キャッシュ、ピボット、レポートのセルはまとめて変わるか、どれも変わらないかのどちらかです。
更新後の cache.listFields() は、各フィールドの name と型のフラグ containsNumber、containsInteger、containsString、containsBlank、containsDate、containsMixedTypes、containsSemiMixedTypes、containsNonDate(Python は contains_number など)を返します。
refresh() は次の場合に例外を投げます。
- ソースを解決できないとき、
StatusCode.PreconditionFailedを投げます。ソースがない場合、外部ソースやワークシート以外のソースの場合、シート、定義名、テーブルが見つからない場合、#REF!や動的な定義名の場合がこれに当たります。 - ソースの (行数 − 1) × 列数がレコードのセル数の上限を超える場合は
StatusCode.SecurityResourceLimitです。
更新は Excel と同じ規則で日付を判定します。
- すべてが日付ではなくなったフィールド(ただの数値や混在)にある日付フィルターは破棄され、すべての行が表示されます。
- 基のフィールドがすべて日付ではなくなった日付グループは、そのグループフィールドと軸への配置ごと削除されます。日付グループの境界が欠けているか読めない場合は、自動の境界に計算し直します。
- 年単位、または 1 日より長い日数間隔のグループで、日付がグループの境界を越えた場合は、グループ化と同じ規則でグループの項目を作り直します。ピボットのフィールドは、ラベルが残る項目を元の順序のまま保ち、その後に新しい項目を並べます。
cache.getWorksheetSource() は range を SheetRect で返します。その sheet はシートのインデックスなので、表示するシート名は wb.sheet(range.sheet).name で得られます。読み取ったレコードは、そのまま setWorksheetSource に渡せます。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B3' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const source = cache.getWorksheetSource()
console.log(wb.sheet(source.range.sheet).name, source.range.rect.lastRow) // Sheet1 2
// A source read back passes to setWorksheetSource as is.
const copy = wb.addPivotCache()
copy.setWorksheetSource(source)
copy.refresh()
console.log(copy.getRecordCount()) // 2from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B3'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
source = cache.get_worksheet_source()
print(wb.sheet(source.range.sheet).name, source.range.rect.last_row) # Sheet1 2
# A source read back passes to set_worksheet_source as is.
copy = wb.add_pivot_cache()
copy.set_worksheet_source(source)
copy.refresh()
print(copy.get_record_count()) # 2wb.formatReference(range) は、ソースをシート名付きの A1 形式のテキストにします。この例は formatReference が SheetRect を受け取るエンジンのリリースを必要とするため、まだ実行していません。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B3' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const source = cache.getWorksheetSource()
// @ts-expect-error
if (source?.range) console.log(wb.formatReference(source.range)) // Sheet1!A1:B3from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B3'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
print(wb.format_reference(cache.get_worksheet_source().range)) # Sheet1!A1:B3キャッシュはソースの変更に自動では追従しません。ソースのセルを変えても、refresh() をもう一度実行するまでピボットは古い数値のままです。次の例は定義名から読み込みます。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
wb.setDefinedName({ name: 'SalesData', formula: 'Sheet1!$A$1:$B$3' })
const cache = wb.addPivotCache()
cache.setWorksheetSource({ name: 'SalesData' })
cache.refresh()
const pivot = ws.addPivot({ name: 'ByRegion', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
console.log(ws.getValue('E2')) // 10
ws.setValue('B2', 25)
console.log(ws.getValue('E2')) // 10
cache.refresh() // re-reads SalesData and rewrites the report
console.log(ws.getValue('E2')) // 25from formulon import (
DefinedNameInput, PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30]])
wb.set_defined_name(DefinedNameInput('SalesData', 'Sheet1!$A$1:$B$3'))
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(name='SalesData'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='ByRegion', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
print(ws['E2']) # 10.0
ws['B2'] = 25
print(ws['E2']) # 10.0
cache.refresh() # re-reads SalesData and rewrites the report
print(ws['E2']) # 25.0ソースがいま指している範囲
cache.getWorksheetSourceRange()(Python は get_worksheet_source_range())は、ソースがいま解決されるシートと矩形を返します。これは refresh() が読む範囲です。テーブルなら見出し行から最後のデータ行まで(集計行は含みません)、定義名ならその現在の範囲、範囲ならそのとおりの範囲です。
ソースが解決できない場合は null を返します。ソースがない、別の種類のソースや別のワークブックのソースである、テーブルや名前が存在しないか 1 つのシート上の 1 つの矩形を指していない、シートが存在しない、のいずれかです。テーブルや名前を削除しても、ソースはその名前のまま残るので、getWorksheetSource().name は名前を返し続け、このメソッドは null を返します。
キャッシュが読むシートを削除しても、Excel と同じく、キャッシュとそのレコード、それを使うすべてのピボットは残ります。ソースは削除されたシートを指したままで、refresh() は StatusCode.PreconditionFailed で失敗します。
更新後の書式
読み込んだピボットテーブルが持つセルの書式とピボットグラフの書式は、Excel と同じく、指しているアイテムと値フィールドに従います。
- 更新するとアイテムの新しい位置へ書式も移ります。
- 更新で消えるアイテム(
missingItemsLimitが 0)や、ソースの列がなくなったフィールドの書式は削除し、見つからないアイテムとして残るアイテムの書式は残します。 - 値フィールドを取り除くと、更新によるものでも、計算フィールドの削除や値エリアからの移動によるものでも、その書式を削除し、後ろの値フィールドの書式を前に詰めます。
- グループ化を解除すると、グループ用フィールドの書式を削除します。数値のグループ化では、元のフィールドの書式も削除します。
pivot.clearFields()はセルの書式をすべて削除し、グラフの書式は残します。
開いたときの更新
開いた .xlsx や .xlsb で refreshOnLoad オプション(cache.getOptions())がオンのキャッシュは、Excel が開くときに更新するのと同じく、ワークブックを最初に読み取り、編集、計算、保存する前にソースから更新します。
読み込みの直後にプロファイルを設定した場合(setProfileId、Python は set_profile_id)はそれが先に適用されるので、見出しが空のフィールドの名前と日付グループのラベルはそのプロファイルに従います。ソースのシートがないなどで更新に失敗したキャッシュは、ファイルに保存されていたレコードを保ちます。
API で作ったキャッシュは、更新でレコードを埋めていない限り refreshOnLoad をオンにして保存されるので、開き直したブックでは手で書いたレコードではなく、ソースの内容が表示されます。
キャッシュを手で組み立てる
ワークシートの範囲を使わずにキャッシュを埋めることもできます。cache.addField(name) でフィールドを、cache.addRecord() でレコードを追加し、cache.setRecordValue(record, field, value)(Python は set_record_value)でセルを 1 つずつ書きます。value の型(number、string、boolean、null、Date、ErrorValue)から型別の書き込みを選びます。Date は日付として、数値は数値として保存され、Python の date と datetime も同じ扱いです。
共有アイテムの cache.addFieldSharedItem(field, value) も同じ形です。listFieldSharedItems() の各要素は isDate(Python は is_date)を持ち、日付アイテムの value はシリアル値です。手で組み立てたキャッシュでも、それを使うピボットを保存するにはワークシートソースが必要です。
フィールドが既に持つ値を追加すると、StatusCode.AlreadyExists(Python は AlreadyExistsError)で拒否されます。
import createFormulon, { FormulonError, StatusCode } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const cache = wb.addPivotCache()
cache.addField('Region')
console.log(cache.addFieldSharedItem(0, 'East')) // 0
try {
cache.addFieldSharedItem(0, 'East')
} catch (e) {
if (!(e instanceof FormulonError)) throw e
console.log(formulon.enumName(StatusCode, e.code)) // AlreadyExists
}from formulon import AlreadyExistsError, Workbook
with Workbook.create_default() as wb:
cache = wb.add_pivot_cache()
cache.add_field("Region")
print(cache.add_field_shared_item(0, "East")) # 0
try:
cache.add_field_shared_item(0, "East")
except AlreadyExistsError as e:
print(e.code.name) # ALREADY_EXISTS次の例は、共有アイテムを明示してキャッシュを組み立て、空白のアイテムを、そのインデックスに結び付いた項目を通して隠します。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
const rows = [['Region', 'Sales'], ['East', 10], ['West', 30], [null, 5]]
ws.setValues('A1', rows)
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B4' })
for (const name of rows[0]) cache.addField(name)
for (const item of ['East', 'West', null]) cache.addFieldSharedItem(0, item) // index 2 is the blank
for (const row of rows.slice(1)) {
const record = cache.addRecord()
row.forEach((value, field) => cache.setRecordValue(record, field, value))
}
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
const labels = () => pivot.getLayout().cells.map((cell) => cell.value).join(' | ')
const before = labels()
// Region is on an axis, so it lists its items; find the one bound to shared item 2.
const blank = pivot.listFieldItems(0).findIndex((item) => item.cacheIndex === 2)
pivot.updateFieldItem(/*fieldIndex*/ 0, blank, { visible: false })
console.log(before)
console.log(labels())
// Row Labels | Sum of Sales | East | 10 | West | 30 | (blank) | 5 | Grand Total | 45
// Row Labels | Sum of Sales | East | 10 | West | 30 | Grand Total | 40from formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
rows = [['Region', 'Sales'], ['East', 10], ['West', 30], [None, 5]]
ws.set_values('A1', rows)
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B4'))
for name in rows[0]:
cache.add_field(name)
for item in ('East', 'West', None):
cache.add_field_shared_item(0, item) # index 2 is the blank
for row in rows[1:]:
record = cache.add_record()
for field, value in enumerate(row):
cache.set_record_value(record, field, value)
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
def labels():
return ' | '.join(str(cell.value) for cell in pivot.get_layout().cells)
before = labels()
# Region is on an axis, so it lists its items; find the one bound to shared item 2.
blank = next(i for i, item in enumerate(pivot.list_field_items(0)) if item.cache_index == 2)
pivot.update_field_item(0, blank, visible=False) # field_index=0
print(before)
print(labels())
# Row Labels | Sum of Sales | East | 10.0 | West | 30.0 | (blank) | 5.0 | Grand Total | 45.0
# Row Labels | Sum of Sales | East | 10.0 | West | 30.0 | Grand Total | 40.0キャッシュ項目をインデックスで指定する
軸に置いたフィールドは、その時点で項目を表示順に並べます。各項目は共有項目の cacheIndex を持ちます。pivot.updateFieldItem(field, item, { visible })(Python は update_field_item(field, item, visible=...))で項目を表示・非表示にします。item は listFieldItems(field) での位置です。空白項目はこの方法で指定します。空のラベルは文字列の照合になり、項目を特定できないためです。
pivot.addFieldItem(field, { cacheIndex }) / add_field_item(field, cache_index=...) は、フィールドがまだ並べていない共有項目インデックスに手動フィルターの項目を結び付けます。すでに並んでいる項目には StatusCode.AlreadyExists(Python は AlreadyExistsError)で失敗します。インデックスは OOXML のピボット項目 x 属性と同じ 0 始まりです。評価前にキャッシュを構築しておくと、意図した項目に一致します。
refresh() の後、軸に置いたフィールドには共有アイテムが作られ、listFieldSharedItems でそれぞれのインデックスを調べられます。どの軸にもないフィールドには共有アイテムがありません。解決できないインデックスは、追加した時点では受け付けられて何も絞り込まず、ワークブックの保存時にはそのアイテムが省かれます。
import createFormulon, { PivotAggregation, PivotAxis } from '@libraz/formulon'
const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
ws.setValues('A1', [['Region', 'Sales'], ['East', 10], ['West', 30], [null, 5]])
const cache = wb.addPivotCache()
cache.setWorksheetSource({ range: 'Sheet1!A1:B4' })
cache.refresh()
const pivot = ws.addPivot({ name: 'SalesSummary', cacheId: cache.cacheId, anchor: 'D1' })
pivot.setFieldAxis('Region', PivotAxis.Row)
pivot.addDataField({ fieldIndex: 'Sales', aggregation: PivotAggregation.Sum })
// Region is on an axis, so it has shared items.
const items = cache.listFieldSharedItems(0).map((item) => item.value)
console.log(items) // [ 'East', 'West', null ]
const blank = pivot.listFieldItems(0).findIndex((item) => item.cacheIndex === items.indexOf(null))
pivot.updateFieldItem(/*fieldIndex*/ 0, blank, { visible: false })
console.log(JSON.stringify(ws.getValues('D1:E4')))
// There is no shared item 9: the item is accepted, and left out on save.
pivot.addFieldItem(0, { cacheIndex: 9 }, { visible: false })
const listsNine = (p) => p.listFieldItems(0).some((item) => item.cacheIndex === 9)
using reloaded = formulon.Workbook.load(wb.save())
console.log(listsNine(pivot), listsNine(reloaded.sheet(0).pivot(0)))
// [["Row Labels","Sum of Sales"],["East",10],["West",30],["Grand Total",40]]
// true falsefrom formulon import (
PivotAggregation, PivotAxis, PivotDataFieldInput, PivotInput,
PivotWorksheetSourceInput, Workbook,
)
with Workbook.create_default() as wb:
ws = wb[0]
ws.set_values('A1', [['Region', 'Sales'], ['East', 10], ['West', 30], [None, 5]])
cache = wb.add_pivot_cache()
cache.set_worksheet_source(PivotWorksheetSourceInput(range='Sheet1!A1:B4'))
cache.refresh()
pivot = ws.add_pivot(PivotInput(name='SalesSummary', cache_id=cache.cache_id, anchor='D1'))
pivot.set_field_axis('Region', PivotAxis.ROW)
pivot.add_data_field(PivotDataFieldInput(field_index='Sales', aggregation=PivotAggregation.SUM))
# Region is on an axis, so it has shared items.
items = [item.value for item in cache.list_field_shared_items(0)]
print(items) # ['East', 'West', None]
blank = next(i for i, item in enumerate(pivot.list_field_items(0)) if item.cache_index == items.index(None))
pivot.update_field_item(0, blank, visible=False) # field_index=0
print(ws.get_values('D1:E4'))
# There is no shared item 9: the item is accepted, and left out on save.
pivot.add_field_item(0, cache_index=9, visible=False)
data = wb.save()
in_session = any(item.cache_index == 9 for item in pivot.list_field_items(0))
with Workbook.load(data) as reloaded:
print(in_session, any(item.cache_index == 9 for item in reloaded[0].pivot(0).list_field_items(0)))
# [['Row Labels', 'Sum of Sales'], ['East', 10.0], ['West', 30.0], ['Grand Total', 40.0]]
# True Falseピボットキャッシュのワークシート参照
API で新しく作成したピボットテーブルは、保存前にキャッシュのワークシートソースを設定する必要があります。JavaScript では PivotCache ハンドルの cache.setWorksheetSource({ range: 'A1:C10', sheet: 'Data' })、Python では cache.set_worksheet_source(PivotWorksheetSourceInput(range='A1:C10', sheet='Data')) を使います(sheet はシート名のない range を修飾し、修飾済みの範囲のシートと食い違うと StatusCode.InvalidArgument で失敗します)。setWorksheetSource(null)(Python は set_worksheet_source(None))でソースを消去します。
getWorksheetSource() はキャッシュにソースがなければ null を返し、あれば range(SheetRect。参照がない、または存在しないシートを指す場合は null)と name を持つソースを返します。シートが空でも宣言した範囲があれば十分です。
ワークシートソースのない新規キャッシュをピボットが使っていると、保存は失敗します。どのピボットも使っていないキャッシュは、保存したファイルに含まれません。ファイルから読み込んだキャッシュには対応するソース情報が残りますが、元がワークシート以外や外部ソースの場合もあります。