透视图
使用透视图之前,需要先注册透视表和图表依赖,然后在创建工作簿之前添加以下两个插件。UI 语言包需要合并到 locales 配置中,并加载对应的样式表。该功能需要 Pro 许可证。
pnpm add @univerjs-pro/sheets-pivot-chart @univerjs-pro/sheets-pivot-chart-uinpm install @univerjs-pro/sheets-pivot-chart @univerjs-pro/sheets-pivot-chart-uiyarn add @univerjs-pro/sheets-pivot-chart @univerjs-pro/sheets-pivot-chart-uibun add @univerjs-pro/sheets-pivot-chart @univerjs-pro/sheets-pivot-chart-uiimport { UniverSheetsPivotChartPlugin } from '@univerjs-pro/sheets-pivot-chart'import { UniverSheetsPivotChartUIPlugin } from '@univerjs-pro/sheets-pivot-chart-ui'import SheetsPivotChartLocale from '@univerjs-pro/sheets-pivot-chart-ui/locale/zh-CN'import { LocaleType } from '@univerjs/core'import '@univerjs-pro/sheets-pivot-chart/facade'import '@univerjs-pro/sheets-pivot-chart-ui/lib/index.css'univerAPI.loadLocales(LocaleType.ZH_CN, SheetsPivotChartLocale)univer.registerPlugin(UniverSheetsPivotChartPlugin)univer.registerPlugin(UniverSheetsPivotChartUIPlugin)Sheets 高级预设已包含这两个插件,可与核心预设、绘图预设一起使用。本页介绍的 API 还需显式导入 @univerjs-pro/sheets-pivot-chart/facade。
配置 Worker
预设配置
以下配置项属于 UniverSheetsAdvancedPreset:
useWorkerboolean默认值:false在公式 Worker 中启用高级功能。
使用 Worker 时,主线程传入 UniverSheetsAdvancedPreset({ useWorker: true }),Worker 内部传入 UniverSheetsAdvancedWorkerPreset()。插件模式的细节见包参考。
独立报表
在独立报表模式下,报表由图表自身持有。插入图表后需要添加一个行字段和一个值字段,示例使用数据源的前两列。
const workbook = univerAPI.getActiveWorkbook()const sheet = workbook?.getActiveSheet()if (!sheet) throw new Error('No active worksheet')sheet.getRange('A1:B4').setValues([ ['Region', 'Sales'], ['East', 100], ['West', 200], ['East', 50],])const chart = await sheet.insertPivotChart( sheet.newPivotChart(univerAPI.Enum.ChartTypeString.Column) .setSource('A1:B4').setPosition('D2').setSize(640, 360).build(),)const fields = chart.getSourceFieldsInfo()await chart.addField(fields[0].id, univerAPI.Enum.PivotTableFiledAreaEnum.Row, 0)await chart.addField(fields[1].id, univerAPI.Enum.PivotTableFiledAreaEnum.Value, 0)关联透视表
字段、筛选、排序和折叠的修改会与所关联的透视表以及该透视表上的其他关联图表同步,外观和位置则保持独立。删除图表不会删除透视表;删除透视表后图表将不可用,直到恢复同一个透视表。
const pivotTable = workbook.getPivotTableById('pivot-table-1')if (!pivotTable) throw new Error('PivotTable not found')const linkedChart = await sheet.insertPivotChart( pivotTable.newChart(univerAPI.Enum.ChartTypeString.Line).setPosition('D22').build(),)linkedChart.setFieldButtonsVisible(true).setExpandCollapseButtonsVisible(true)支持的图表类型
支持折线、柱形、条形、面积、饼图、圆环和组合图,以及适用的堆积类型。不支持散点、气泡、雷达和瀑布图。饼图使用第一个值系列,圆环图保留多个系列。图表分类中不包含小计和总计。
字段、筛选、样式和生命周期 API 见 FSheetPivotChart。
复制和删除工作表
复制工作表时,其中的透视图也会一并复制,并获得新的 ID。如果独立报表的数据源位于被复制的工作表上,副本将使用新的工作表和独立的缓存。当透视表随工作表一起复制时,关联透视图会指向复制后的透视表;对其他工作表的引用保持不变。删除工作表会移除其中的透视图及其相关资源,撤销操作可以恢复它们的定义和源数据。
报表筛选
getOptions()、setOptions({ allowMultipleFilters: true }) 和 setDateFilter(fieldId, condition) 作用于图表实际使用的报表。对于关联图表,这些方法会更新源透视表及其他关联图表;对于独立图表,这些方法只更新该图表自身的报表。省略 condition 只清除日期条件。日期序列值和整日比较的说明见多重筛选与日期条件。
你觉得这篇文档如何?