Tabla dinámica

Las tablas dinámicas son una poderosa herramienta de análisis de datos que permite a los usuarios resumir, analizar y visualizar rápidamente grandes cantidades de datos. Admite varias operaciones de datos y opciones de formato para ayudar a los usuarios a comprender mejor sus datos.

Introducción

Las tablas dinámicas de datos se usan generalmente en los siguientes escenarios:

  • Resumir datos: las tablas dinámicas pueden ayudarlo a resumir rápidamente los datos para comprender mejor la situación general.
  • Analizar datos: las tablas dinámicas pueden ayudarlo a analizar datos para identificar patrones y relaciones.
  • Explorar datos: las tablas dinámicas pueden ayudarlo a explorar datos para descubrir reglas y tendencias.
  • Visualización de datos: las tablas dinámicas pueden ayudarle a visualizar datos para una mejor comprensión.

Una tabla dinámica generalmente incluye los siguientes elementos:

  • Etiquetas de filas: las etiquetas de filas en una tabla dinámica se usan para agrupar datos.
  • Etiquetas de columnas: las etiquetas de columnas en una tabla dinámica se usan para agrupar datos.
  • Valores: los valores en una tabla dinámica se usan para resumir datos.

En una tabla dinámica, puede ajuste las etiquetas de fila, las etiquetas de columna y los valores según sea necesario para analizar mejor los datos.

Fuente de datos

En Univer Sheets, la fuente de datos para una tabla dinámica puede ser una hoja de trabajo o un rango de datos. Puede elegir diferentes fuentes de datos según sea necesario para analizar mejor sus datos. Tomamos la primera fila de la fuente de datos como etiquetas de columna predeterminadas y el resto como fuente de datos. Por lo tanto, requerimos que la fuente de datos esté lo más organizada posible, evitando filas y columnas vacías tanto como sea posible. Para los datos en la misma columna, reconoceremos automáticamente el tipo de datos para admitir mejor la funcionalidad de la tabla dinámica. Si el tipo de datos es inconsistente en una columna, estableceremos de forma predeterminada el tipo de datos de esa columna como cadena.

En Univer Sheets, las tablas dinámicas responderán automáticamente a los cambios en los datos. Cuando cambie la fuente de datos, la tabla dinámica se actualizará automáticamente para analizar mejor los datos.

Filtrado

Las tablas dinámicas de datos admiten el filtrado por etiquetas de filas y columnas, y también proporcionan un campo de filtro que no participa en la clasificación de datos principal ni en el diseño de resumen de la tabla dinámica, pero se puede usar para filtrar datos.

Las tablas dinámicas de datos admiten dos métodos de filtrado:

  • Filtrado de etiquetas: el filtrado de etiquetas se aplica directamente a los elementos de la dimensión de etiqueta actual. Por ejemplo, en la dimensión de provincia, podemos filtrar ciertas provincias.
  • Filtrado de valores: el filtrado de valores requiere especificar una dimensión de valor y luego filtrar los resultados resumidos del campo de valor. Por ejemplo, podemos filtrar datos con ventas inferiores a 1000.

Clasificación

La clasificación de la tabla dinámica de datos solo tiene efecto en los campos de fila/columna y admite orden ascendente y descendente. El método de clasificación utiliza el método localCompare. En el futuro, admitiremos más métodos de clasificación, como la clasificación pinyin.

Las tablas dinámicas de datos admiten dos métodos de clasificación:

  • Clasificación de etiquetas: la clasificación de etiquetas se aplica directamente a los elementos de la dimensión de etiqueta actual. Por ejemplo, en la dimensión de provincia, podemos ordenar por nombre de provincia.
  • Clasificación de valores: la clasificación de valores requiere especificar una dimensión de valor y luego ordenar los resultados resumidos del campo de valor. Por ejemplo, podemos ordenar por monto de ventas.

Agregación

Las tablas dinámicas de datos admiten 11 métodos de agregación admitidos por Excel, que incluyen: suma, recuento, recuento de datos, promedio, máximo, mínimo, factorial, desviación estándar, varianza, desviación estándar de población y varianza de población.

Las tablas dinámicas de datos admiten múltiples dimensiones de valor y permiten la personalización del área de dimensión de valor (posición de valor) y la posición (índice de valor).

Esta es una lógica de diseño compleja, por lo que solo vista de tabla de soporte por ahora. En el futuro, admitiremos más vistas según la demanda.

Profundizar

Profundizar se refiere a la capacidad de los usuarios de hacer doble clic en una celda en el área de valores de una tabla dinámica para ver los datos detallados correspondientes a esa celda. Por ejemplo, los usuarios pueden hacer clic en una celda de la tabla dinámica para ver los datos detallados detrás de ella, lo que permite un mejor seguimiento de los datos originales.

Agrupación

Las tablas dinámicas de datos admiten la funcionalidad de agrupación, que aún no es compatible con Univer Sheets.

La agrupación se puede realizar de las siguientes maneras:

  • Agrupación por fechas: esto implica agrupar datos de fechas por año, mes, día, etc.
  • Agrupación numérica: esto implica agrupar datos numéricos en rangos específicos.
  • Agrupación de elementos: esto implica agrupar datos de elementos de acuerdo con reglas específicas.

Modo de complemento

Instalación

Shell
pnpm add @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui

Uso

TypeScript
import { UniverSheetsPivotTablePlugin } from '@univerjs-pro/sheets-pivot'import { UniverSheetsPivotTableUIPlugin } from '@univerjs-pro/sheets-pivot-ui'import SheetsPivotTableUIEnUS from '@univerjs-pro/sheets-pivot-ui/locale/en-US'import SheetsPivotTableEnUS from '@univerjs-pro/sheets-pivot/locale/en-US'import { LocaleType, mergeLocales, Univer } from '@univerjs/core'import '@univerjs-pro/sheets-pivot-ui/lib/index.css'import '@univerjs-pro/sheets-pivot/facade' // [!codeconst univer = new Univer({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      SheetsPivotTableEnUS,       SheetsPivotTableUIEnUS,     ),  },})

Registro Complementos

El complemento de tabla dinámica admite el registro flexible para diferentes escenarios de uso, proporcionando dos modos para adaptarse a diversas necesidades computacionales.

Registro solo en el proceso principal

El complemento de tabla dinámica solo se puede registrar en el proceso principal. Este modo es adecuado para tareas livianas, operaciones simples y no requiere configuración adicional de la configuración del complemento. Los desarrolladores solo necesitan importar UniverSheetsPivotTablePlugin.

TypeScript
univer.registerPlugin(UniverSheetsPivotTablePlugin)univer.registerPlugin(UniverSheetsPivotTableUIPlugin)

Registrarse tanto en el proceso principal como en el de trabajo

Para escenarios que requieren un alto rendimiento, el complemento de tabla dinámica admite el registro tanto en el proceso principal como en el de trabajo. Este modo permite que el complemento aproveche una arquitectura de subprocesos múltiples para una distribución de datos y un procesamiento de cálculo eficientes, lo que reduce significativamente la carga computacional del proceso principal y mejora el rendimiento general.

En este modo, el proceso principal es el principal responsable de la distribución, sincronización y representación de datos, mientras que el proceso de trabajo se centra en tareas computacionales complejas. Para implementar este modo, se requiere un ajuste fino de la configuración durante el registro a través de la configuración.

TypeScript
// main process file// Setting notExecuteFormula to true indicates that the main process does not perform calculations. It is only responsible for data distribution, synchronization, and rendering.univer.registerPlugin(UniverSheetsPivotTablePlugin, { notExecuteFormula: true })univer.registerPlugin(UniverSheetsPivotTableUIPlugin)// web worker process file// Setting notExecuteFormula to false indicates that the worker process performs the calculations.univer.registerPlugin(UniverSheetsPivotTablePlugin, { notExecuteFormula: false })

Si tiene una licencia comercial para Univer, consulte Uso de licencia en el cliente para la configuración.

Complementos y configuración

TypeScript
interface IUniverSheetsPivotConfig {  /**   * Define the maximum number of items that can be displayed in a single pivot table field.   * @default 1000   */  maxLimitItemCount?: number}

Compatibilidad móvil

Configure primero el editor móvil. En la inicialización en modo plugin de esta página, sustituya los registros de escritorio siguientes por las exportaciones móviles de los mismos paquetes antes de abrir un documento. Conserve modelos, estilos, traducciones e importaciones Facade; no registre ambas variantes.

PaqueteRegistro de escritorioRegistro móvil
@univerjs-pro/sheets-pivot-uiUniverSheetsPivotTableUIPluginUniverSheetsPivotTableMobileUIPlugin

Preestablecido Modo

La función de tabla dinámica está incluida en el ajuste preestablecido @univerjs/preset-sheets-advanced, que también incluye otras funciones avanzadas como dibujo y marca de agua.

Instalación

El ajuste preestablecido UniverSheetsAdvancedPreset de @univerjs/preset-sheets-advanced depende del ajuste preestablecido UniverSheetsDrawingPreset en tiempo de ejecución. Primero instale @univerjs/preset-sheets-drawing.

Shell
pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced

Uso

TypeScript
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US'import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-drawing/lib/index.css'import '@univerjs/preset-sheets-advanced/lib/index.css'const { univerAPI } = createUniver({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      UniverPresetSheetsCoreEnUS,      UniverPresetSheetsDrawingEnUS,       UniverPresetSheetsAdvancedEnUS,     ),  },  presets: [    UniverSheetsCorePreset(),    UniverSheetsDrawingPreset(),     UniverSheetsAdvancedPreset(),   ],})

Si tiene una licencia comercial para Univer, consulte Uso de la licencia en el cliente para la configuración.

Preajustes y configuración

TypeScript
interface IUniverSheetsAdvancedPresetConfig {  pivot?: Pick<IUniverSheetsPivotConfig, 'maxLimitItemCount'>}interface IUniverSheetsPivotConfig {  /**   * Define the maximum number of items that can be displayed in a single pivot table field.   * @default 1000   */  maxLimitItemCount?: number}

API de Facade

Las definiciones completas del tipo de API de Facade se pueden encontrar en la FacadeAPI.

Importar

Plugin mode note

Solo el modo complemento requiere importar manualmente el paquete Facade. El modo preestablecido ya incluye el paquete Facade correspondiente, por lo que no se necesita ninguna importación adicional.

TypeScript
import '@univerjs-pro/sheets-pivot/facade'

Agregar una tabla dinámica

El método FWorkbook.addPivotTable se utiliza para agregar una tabla dinámica y devolverá la instancia FPivotTable si tiene éxito.

TypeScript
// should ensure the sheet range A1:G9 is not emptyconst fWorkbook = univerAPI.getActiveWorkbook()const unitId = fWorkbook.getId()const fSheet = fWorkbook.getActiveSheet()const subUnitId = fSheet.getSheetId()const sheetName = fSheet.getSheetName()const sourceInfo = {  unitId,  subUnitId,  sheetName,  range: {    startRow: 0,    startColumn: 0,    endRow: 8,    endColumn: 6,  },}const anchorCellInfo = {  unitId,  subUnitId,  row: 20,  col: 8,}const fPivotTable = await fWorkbook.addPivotTable(sourceInfo, univerAPI.Enum.PositionTypeEnum.Existing, anchorCellInfo)const pivotTableId = fPivotTable.getPivotTableId()// add flag to avoid add pivot fields multiple timeslet hasAdded = false// the addPivotTable is async, you can add pivot fields after the pivot table is addeduniverAPI.addEvent(univerAPI.Event.PivotTableRendered, (params) => {  if (!hasAdded && params.pivotTableId === pivotTableId) {    fPivotTable.addField(1, univerAPI.Enum.PivotTableFiledAreaEnum.Row, 0)    fPivotTable.addField(1, univerAPI.Enum.PivotTableFiledAreaEnum.Value, 0)    hasAdded = true  }})

Obtener una tabla dinámica Tabla

El método FWorkbook.getPivotTableByCell se utiliza para obtener una instancia de tabla dinámica mediante la celda ancla, y devolverá la instancia FPivotTable si la celda de destino está en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const unitId = fWorkbook.getId()const fSheet = fWorkbook.getActiveSheet()const subUnitId = fSheet.getSheetId()// get pivot table by the cell in FWorkbook.const fPivotTable = fWorkbook.getPivotTableByCell(unitId, subUnitId, 0, 8)// get pivot table by the cell in FWorksheet.const pivotTable2 = fSheet.getPivotTableByCell(0, 8)

Hay algunos métodos en la instancia FPivotTable, que se pueden usar para operar la tabla dinámica.

MétodoDescripción
removeeliminar la tabla dinámica de la instancia
getConfigdevolver la configuración de la tabla dinámica, la información del rango de origen, la información de la celda de anclaje y la configuración
addFieldagregar un campo a la tabla dinámica
removeFieldeliminar un campo de la tabla dinámica
updateFieldPositionactualizar la posición del campo en la tabla dinámica
updateValuePositioncontrolar la ∑posición del valor
setSubtotalTypeestablecer el tipo de subtotal del campo
setLabelSortestablecer el tipo de etiqueta del campo
setLabelManualFilterestablecer el filtro de etiqueta del campo
renameFieldcambiar el nombre del campo
setValueFilterestablecer filtro de valor
resetrestablecer los campos de la tabla dinámica
setFieldsConfigestablecer la configuración de los campos de la tabla dinámica
getValueFiltersobtener todos los filtros de valor de la tabla dinámica
TypeScript
class FPivotTable {/** * @description Get the pivot table config by the pivot table id. * @typedef PivotTableConfig * @property {TargetInfo} targetCellInfo  The target cell info of the pivot table. * @property {SourceInfo} sourceRangeInfo The source data range info of the pivot table. * @property {boolean} isEmpty The pivot table is empty or not. * @property {object} fieldsConfig The snapshot of the pivot table fields config. * @returns {PivotTableConfig|undefined} The pivot table config or undefined. */  getConfig(): IPivotTableConfig  /**   * @description Remove a pivot table from the workbook by pivot table id   */  async remove(): void  /**   *@description Add a pivot field to the pivot table.   * @param {string|number} dataFieldIdOrIndex The data field id.   * @param {PivotTableFiledAreaEnum} fieldArea The area of the field.   * @param {number} index The index of the field in the target area.   * @returns {boolean} Whether the pivot field is added successfully.   */  async addField(dataFieldIdOrIndex: string | number, fieldArea: PivotTableFiledAreaEnum, index: number): Promise<boolean>  /**   * @description Remove a pivot field from the pivot table   * @param {string[]} fieldIds The deleted field ids.   * @returns {boolean} Whether the pivot field is removed successfully.   */  async removeField(fieldIds: string[]): Promise<boolean>  /**   * @description Update the pivot table field position.   * @param {string} fieldId - The moved field id.   * @param {PivotTableFiledAreaEnum} area - The target area of the field.   * @param {number} index - The target index of the field, if the index is bigger than the field count in the target area, the field will be moved to the last, if the index is smaller than 0, the field will be moved to the first.   * @returns {boolean} Whether the pivot field is moved successfully.   */  async updateFieldPosition(fieldId: string, area: PivotTableFiledAreaEnum, index: number): Promise<boolean>  /**   * @description If there are multiple value fields in the pivot table, you can update the position of the value field, which only can be position in row or column.   * @param {PivotTableValuePositionEnum} position - The position of the value field.   * @param {number} index - The index of the value field.   * @returns {boolean} Whether the pivot value field is moved successfully.   */  async updateValuePosition(position: PivotTableValuePositionEnum, index: number): Promise<boolean>  /**   * @description Set the pivot table subtotal type for value field, it only works for the value field.   * @param {string} fieldId - The field id.   * @param {PivotSubtotalTypeEnum} subtotalType - The subtotal type of the field.   * @returns {boolean} Whether the pivot table subtotal type is set successfully.   */  async setSubtotalType(fieldId: string, subtotalType: PivotSubtotalTypeEnum): Promise<boolean>  /**   * @description Set the pivot table sort info.   * @param {string} tableFieldId - The field id of the sort.   * @param {PivotTableSortInfo} info - The sort info.   * @typedef PivotTableSortInfo   * @property {PivotDataFieldSortOperatorEnum} type The sort operator of the field items.   * @returns {boolean} Whether the pivot table sort info is set successfully.   */  async setLabelSort(tableFieldId: string, info: IPivotTableSortInfo): Promise<boolean>  /**   * @description Set the pivot table filter.   * @param {string} tableFieldId - The field id of the filter.   * @param {string[]} items - The items of the filter.   * @returns {boolean} Whether the pivot table filter is set successfully.   */  async setLabelFilter(tableFieldId: string, items: string[], isAll?: boolean): Promise<boolean>  /**   * @description Rename the pivot table field.   * @param {string} fieldId - The field id.   * @param {string} name - The new name of the field.   * @returns {boolean} Whether the pivot table field is renamed successfully.   */  async renameField(fieldId: string, name: string): Promise<boolean>  /**   * @description Set the pivot table value filter. A value filter is used to filter the data based on the value of a field.   * @param {string} fieldId - The field id of the filter. Only one value filer can be set for a field.   * @param {Omit<IPivotTableValueFilter, 'type'>} filterInfo - The filter info. The undefined value will be removed from the old filter.   * @typedef filterInfo   * @property {valueGreaterThan} operator - The filter operator is used to compare the value of the field with the expected value.Currently, The following operators are supported: valueBetween, valueEqual, valueGreaterThan, valueGreaterThanOrEqual, valueLessThan, valueLessThanOrEqual,valueNotBetween,valueNotEqual.   * @property {number} expected - The expected value.   * @property {string} valueFieldId - The value field id.   * @returns {boolean} Whether the pivot table value filter is set successfully.   */  async setValueFilter(fieldId: string, filterInfo: Omit<IPivotTableValueFilter, 'type'>): Promise<boolean>  /**   * @description Clear the fields by provided field area or clear all fields.   * @param {PivotTableFiledAreaEnum} [resetArea] The area of the field to reset or undefined to reset all fields.   * @returns {Promise<boolean>} Whether the pivot table fields are reset successfully.   */  reset(resetArea?: PivotTableFiledAreaEnum): Promise<boolean>  /**   * @description Set the pivot table fields config.It will add fields to the pivot table from provided config.Before setting the fields config, you should ensure the pivot table is empty to avoid the conflict.   * @param {IPivotTableConfig['fieldsConfig']} config The pivot table fields config.   * @returns {Promise<boolean>} Whether the pivot table fields config is set successfully.   */  setFieldsConfig(config: IPivotTableConfig['fieldsConfig']): Promise<boolean>  /**   * Get all value filters of the pivot table. In pivot table, the value filter must be applied in order.So the order of the value filter is important.   * @returns {IValueFilterInfoItem[]} The value filter info list.   */  getValueFilters(): IValueFilterInfoItem[]}

Escuchas de eventos

Las definiciones completas de tipos de eventos se pueden encontrar en Eventos.

Se activa el evento univerAPI.Event.BeforePivotTableAdd antes de agregar una tabla dinámica.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforePivotTableAdd, (params) => {  const { positionType, targetCellInfo } = params  if (positionType === univerAPI.Enum.PositionTypeEnum.Existing && targetCellInfo.sheetName === 'Sheet 1') {    // Cancel the pivot table adding operation    params.cancel = true    console.log(`The pivot table can't be added to the sheet ${targetCellInfo.sheetName}`)  }})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableAdded se activa después de agregar una tabla dinámica.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableAdded, (params) => {  const { positionType, targetCellInfo } = params  if (positionType === univerAPI.Enum.PositionTypeEnum.Existing) {    console.log('A pivot table created in an existing sheet')    console.log(`      The target sheet name is ${targetCellInfo.sheetName},      the target row is ${targetCellInfo.row}, the target column is ${targetCellInfo.column}    `)  } else {    console.log('A pivot table created in a new sheet')  }})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.BeforePivotTableMove se activa antes de mover una tabla dinámica.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforePivotTableMove, (params) => {  const { pivotTableId, targetCellInfo } = params  if (pivotTableId === 'pivotTable1' && targetCellInfo.sheetName === 'Sheet 1') {    // Cancel the move pivot table operation    params.cancel = true    console.log(`The pivot table can't be moved to the sheet ${targetCellInfo.sheetName}`)  }})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableMoved se activa después de mover una tabla dinámica.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableMoved, (params) => {  const { pivotTableId, targetCellInfo, originTargetInfo } = params  if (pivotTableId === 'pivotTable1') {    console.log(`      The pivot table moved from row: ${originTargetInfo.row} & column: ${originTargetInfo.column}      to the sheet ${targetCellInfo.sheetName} row: ${targetCellInfo.row} & column: ${targetCellInfo.column}    `)  }})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableRendered se activa después de representar una tabla dinámica table.

TypeScript
// import { unionPivotViewRange } from '@univerjs-pro/sheets-pivot';const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableRendered, (params) => {  const { pivotTableId, rangeInfo } = params  console.log(`The pivot table ${pivotTableId} has been rendered`)  if (rangeInfo) {    console.log(unionPivotViewRange(rangeInfo))  }})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableRemoved se activa después de eliminar una tabla dinámica.

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableRemoved, (params) => {  const { pivotTableId } = params  console.log(`The pivot table ${pivotTableId} has been removed`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldAdded se activa después de agregar un campo a una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldAdded, (params) => {  const { pivotTableId, fieldId, fieldArea, fieldIndex } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting('fieldId')  console.log(fieldSetting)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldRemoved se activa después de eliminar un campo de una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldRemoved, (params) => {  const { pivotTableId, fieldId } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(fieldSetting)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldMoved se activa después de mover un campo en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldMoved, (params) => {  const { pivotTableId, fieldId, fieldArea, fieldIndex } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldCollapseChanged se activa después de expandir/contraer una dimensión en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldCollapseChanged, (params) => {  const { pivotTableId, fieldId, isCollapsed } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldFilterChanged se activa después de filtrar una dimensión en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldFilterChanged, (params) => {  const { pivotTableId, fieldId, filter } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The Checklist filter value is ${fieldSetting.filterInfo.checklist}`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldSortChanged se activa después de ordenar una dimensión en una tabla dinámica table.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldSortChanged, (params) => {  const { pivotTableId, fieldId, sort } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The sort info is ${fieldSetting.sortInfo}`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableFieldSettingChanged se activa después de cambiar la configuración de una dimensión en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableFieldSettingChanged, (params) => {  const { pivotTableId, fieldId, setting } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const fieldSetting = pivotTable.getFieldSetting(fieldId)  console.log(`The source name ${fieldSetting.sourceName} the display name ${fieldSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

El evento univerAPI.Event.PivotTableValuePositionChanged se activa después de cambiar la posición de un valor en una tabla dinámica.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const disposable = univerAPI.addEvent(univerAPI.Event.PivotTableValuePositionChanged, (params) => {  const { pivotTableId, valueId, position } = params  const pivotTable = fWorkbook.getPivotTableById(pivotTableId)  const valueSetting = pivotTable.getValueSetting(valueId)  console.log(`The source name ${valueSetting.sourceName} the display name ${valueSetting.displayName}`)})// Remove the event listener, use `disposable.dispose()`

Mostrar valores como

Usa setShowDataAs() en un campo de valores para mostrar su porcentaje del total de una fila, columna o tabla, o la diferencia respecto a un elemento base. Cambia el cálculo mostrado sin sustituir los datos originales. getShowDataAs() consulta la configuración y resetShowDataAs() restaura el cálculo normal.

TypeScript
const valueId = fPivotTable.getFieldIdsByArea(  univerAPI.Enum.PivotTableFiledAreaEnum.Value,)[0]if (valueId) {  await fPivotTable.setShowDataAs(valueId, {    type: univerAPI.Enum.PivotShowAsTypeEnum.percentOfGrandTotal,  })  console.log(fPivotTable.getShowDataAs(valueId))}

fPivotTable representa una tabla dinámica existente. Utiliza el ID de un campo de valores, no el de una columna de origen ni de un campo de filas. Los modos de diferencia y acumulado también requieren configurar el campo y el elemento base.

Copiar tablas dinámicas junto con una hoja

Con el plugin de tablas dinámicas registrado, duplicar una hoja también copia sus tablas dinámicas y la configuración de campos. Cada copia recibe un ID nuevo. Si el origen está en la hoja copiada, la referencia apunta a la nueva hoja; si está en otra hoja o libro, conserva la referencia original. Las tablas copiadas participan en las operaciones de deshacer y rehacer la duplicación de la hoja.

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) throw new Error('No active workbook')const copiedSheet = workbook.duplicateActiveSheet()console.log(copiedSheet.getSheetName())

¿Cómo es esta guía?

© 2026 DreamNum Co., Ltd.