# 피벗 테이블

- Human documentation: [https://docs.univer.ai/ko-KR/guides/sheets/features/pivot-table](https://docs.univer.ai/ko-KR/guides/sheets/features/pivot-table)

- Agent Markdown: [https://docs.univer.ai/ko-KR/guides/sheets/features/pivot-table.md](https://docs.univer.ai/ko-KR/guides/sheets/features/pivot-table.md)

- Requested language: `ko-KR`

- Content language: `ko-KR`

- Documentation version: `1.0.4`

- Source: [sheets/features/pivot-table.ko-KR.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/pivot-table.ko-KR.mdx)

---

#### Package metadata

```json
{
  "mobile": true,
  "preset": [
    {
      "client": "@univerjs/preset-sheets-advanced",
      "locale": "@univerjs/preset-sheets-advanced/locales/ko-KR",
      "style": "@univerjs/preset-sheets-advanced/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs-pro/sheets-pivot",
      "facade": "@univerjs-pro/sheets-pivot/facade",
      "locale": "@univerjs-pro/sheets-pivot/locale/ko-KR"
    },
    {
      "client": "@univerjs-pro/sheets-pivot-ui",
      "locale": "@univerjs-pro/sheets-pivot-ui/locale/ko-KR",
      "style": "@univerjs-pro/sheets-pivot-ui/lib/index.css"
    }
  ],
  "license": true,
  "server": false
}
```

피벗 테이블은 많은 양의 데이터를 빠르게 요약하고 분석하며 시각화할 수 있는 강력한 데이터 분석 도구입니다. 다양한 데이터 작업과 서식 옵션을 지원하여 데이터를 더 쉽게 이해할 수 있도록 도와줍니다.

## 소개

피벗 테이블은 일반적으로 다음과 같은 상황에서 사용합니다.

* 데이터 요약: 데이터를 빠르게 요약하여 전체 현황을 파악할 수 있습니다.
* 데이터 분석: 데이터를 분석하여 패턴과 관계를 찾을 수 있습니다.
* 데이터 탐색: 데이터를 탐색하여 규칙과 추세를 발견할 수 있습니다.
* 데이터 시각화: 데이터를 시각화하여 더 쉽게 이해할 수 있습니다.

피벗 테이블은 일반적으로 다음 요소로 구성됩니다.

* 행 레이블: 데이터를 그룹화하는 데 사용합니다.
* 열 레이블: 데이터를 그룹화하는 데 사용합니다.
* 값: 데이터를 요약하는 데 사용합니다.

피벗 테이블에서는 분석 목적에 맞게 행 레이블, 열 레이블, 값을 조정할 수 있습니다.

![로케일 없음](https://raw.githubusercontent.com/dream-num/documentation/dev/content/guides/sheets/features/pivot-table/pivot.png)

### 데이터 원본

Univer Sheets에서 피벗 테이블의 데이터 원본은 워크시트나 데이터 범위가 될 수 있습니다. 분석 목적에 맞는 데이터 원본을 선택하세요.
데이터 원본의 첫 번째 행은 기본 열 레이블로, 나머지 행은 데이터로 사용합니다. 따라서 데이터 원본은 가능한 한 정돈된 형태로 구성하고 빈 행과 빈 열은 가급적 피해야 합니다.
같은 열에 있는 데이터의 형식은 피벗 테이블 기능을 원활하게 지원할 수 있도록 자동으로 인식합니다. 한 열에 서로 다른 데이터 형식이 섞여 있으면 해당 열의 데이터 형식을 문자열로 처리합니다.

Univer Sheets의 피벗 테이블은 데이터 변경 사항을 자동으로 반영합니다. 데이터 원본이 바뀌면 피벗 테이블도 자동으로 업데이트됩니다.

### 필터링

피벗 테이블은 행 레이블과 열 레이블 필터링을 지원합니다. 또한 피벗 테이블의 주요 데이터 분류 및 요약 레이아웃에는 포함되지 않으면서 데이터를 필터링하는 데 사용할 수 있는 필터 필드도 제공합니다.

피벗 테이블은 두 가지 필터링 방식을 지원합니다.

* 레이블 필터링: 현재 레이블 차원의 항목에 직접 적용합니다. 예를 들어 시·도 차원에서 특정 시·도를 제외할 수 있습니다.
* 값 필터링: 값 차원을 지정한 다음 값 필드의 요약 결과를 필터링합니다. 예를 들어 매출이 1000 미만인 데이터를 제외할 수 있습니다.

### 정렬

피벗 테이블 정렬은 행/열 필드에만 적용되며 오름차순과 내림차순을 지원합니다. 정렬에는 `localCompare` 메서드를 사용합니다. 향후 병음 정렬과 같은 다양한 정렬 방식을 지원할 예정입니다.

피벗 테이블은 두 가지 정렬 방식을 지원합니다.

* 레이블 정렬: 현재 레이블 차원의 항목에 직접 적용합니다. 예를 들어 시·도 차원에서 시·도 이름순으로 정렬할 수 있습니다.
* 값 정렬: 값 차원을 지정한 다음 값 필드의 요약 결과를 정렬합니다. 예를 들어 매출액순으로 정렬할 수 있습니다.

### 집계

피벗 테이블은 Excel에서 제공하는 합계, 개수, 데이터 개수, 평균, 최댓값, 최솟값, 계승, 표준 편차, 분산, 모표준 편차, 모분산 등 11가지 집계 방식을 지원합니다.

피벗 테이블은 여러 값 차원을 지원하며 값 차원 영역(값 위치)과 순서(값 인덱스)를 사용자 지정할 수 있습니다.

레이아웃 로직이 복잡하기 때문에 현재는 테이블 보기만 지원합니다. 향후 요구 사항에 따라 더 다양한 보기를 지원할 예정입니다.

### 드릴다운

드릴다운은 피벗 테이블의 값 영역에 있는 셀을 두 번 클릭하여 해당 셀에 대응하는 상세 데이터를 확인하는 기능입니다. 예를 들어 피벗 테이블의 셀을 클릭하면 그 셀의 기반이 되는 상세 데이터를 확인하여 원본 데이터를 더 쉽게 추적할 수 있습니다.

### 그룹화

피벗 테이블에는 그룹화 기능이 있지만, 아직 Univer Sheets에서는 지원하지 않습니다.

그룹화 방식은 다음과 같습니다.

* 날짜 그룹화: 날짜 데이터를 연도, 월, 일 등으로 그룹화합니다.
* 숫자 그룹화: 숫자 데이터를 지정된 범위로 그룹화합니다.
* 요소 그룹화: 요소 데이터를 특정 규칙에 따라 그룹화합니다.

## 플러그인 모드

### 설치

#### npm

```bash
npm install @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui
```

#### pnpm

```bash
pnpm add @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui
```

#### yarn

```bash
yarn add @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui
```

#### bun

```bash
bun add @univerjs-pro/sheets-pivot @univerjs-pro/sheets-pivot-ui
```

### 사용법

```typescript
import { UniverSheetsPivotTablePlugin } from '@univerjs-pro/sheets-pivot' // [!code ++]
import { UniverSheetsPivotTableUIPlugin } from '@univerjs-pro/sheets-pivot-ui' // [!code ++]
import SheetsPivotTableUIEnUS from '@univerjs-pro/sheets-pivot-ui/locale/en-US' // [!code ++]
import SheetsPivotTableEnUS from '@univerjs-pro/sheets-pivot/locale/en-US' // [!code ++]
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'
import '@univerjs-pro/sheets-pivot-ui/lib/index.css' // [!code ++]
import '@univerjs-pro/sheets-pivot/facade' // [!code

const univer = new Univer({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      SheetsPivotTableEnUS, // [!code ++]
      SheetsPivotTableUIEnUS, // [!code ++]
    ),
  },
})
```

### 플러그인 등록

피벗 테이블 플러그인은 사용 환경에 따라 유연하게 등록할 수 있으며, 계산 요구 사항에 맞게 두 가지 모드를 제공합니다.

**메인 프로세스에만 등록**

피벗 테이블 플러그인을 메인 프로세스에만 등록할 수 있습니다. 이 모드는 가벼운 작업과 단순한 연산에 적합하며 플러그인 config를 별도로 구성하지 않아도 됩니다. 개발자는 `UniverSheetsPivotTablePlugin`만 가져오면 됩니다.

```typescript
univer.registerPlugin(UniverSheetsPivotTablePlugin)
univer.registerPlugin(UniverSheetsPivotTableUIPlugin)
```

**메인 프로세스와 워커 프로세스에 모두 등록**

높은 성능이 필요한 경우 피벗 테이블 플러그인을 메인 프로세스와 워커 프로세스에 모두 등록할 수 있습니다. 이 모드에서는 다중 스레드 아키텍처를 활용하여 데이터를 효율적으로 분배하고 계산하므로 메인 프로세스의 계산 부담을 크게 줄이고 전반적인 성능을 높일 수 있습니다.

이 모드에서 메인 프로세스는 주로 데이터 분배, 동기화, 렌더링을 담당하고 워커 프로세스는 복잡한 계산 작업을 담당합니다. 이 모드를 사용하려면 등록할 때 config를 세부적으로 설정해야 합니다.

```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 })
```

Univer 상용 라이선스가 있다면 [클라이언트에서 라이선스 사용하기](https://docs.univer.ai/ko-KR/server/license.md#in-plugin-mode)를 참고하여 설정하세요.

### 플러그인 및 구성

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

## 모바일 지원

먼저 [모바일 에디터](https://docs.univer.ai/ko-KR/guides/sheets/getting-started/installation.md#mobile-support)를 구성하세요. 이 페이지의 플러그인 모드 초기화 코드에서 아래 데스크톱 등록을 같은 패키지의 모바일 버전으로 바꾸고 **문서를 열기 전에** 완료하세요. 모델 플러그인, 스타일, 언어 파일과 Facade 가져오기는 유지하며 두 버전을 동시에 등록하지 마세요.

| 패키지                             | 데스크톱 등록                          | 모바일 등록                                 |
| ------------------------------- | -------------------------------- | -------------------------------------- |
| `@univerjs-pro/sheets-pivot-ui` | `UniverSheetsPivotTableUIPlugin` | `UniverSheetsPivotTableMobileUIPlugin` |

## 프리셋 모드

피벗 테이블 기능은 `@univerjs/preset-sheets-advanced` 프리셋에 포함되어 있습니다. 이 프리셋에는 그리기, 워터마크와 같은 다른 고급 기능도 포함됩니다.

### 설치

> [!NOTE]
> `@univerjs/preset-sheets-advanced`의 `UniverSheetsAdvancedPreset` 프리셋은 런타임에 `UniverSheetsDrawingPreset` 프리셋을 사용합니다. 먼저 `@univerjs/preset-sheets-drawing`을 설치하세요.

#### npm

```bash
npm install @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### pnpm

```bash
pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### yarn

```bash
yarn add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### bun

```bash
bun add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

### 사용법

```typescript
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced' // [!code ++]
import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US' // [!code ++]
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing' // [!code ++]
import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US' // [!code ++]
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css' // [!code ++]
import '@univerjs/preset-sheets-advanced/lib/index.css' // [!code ++]

const { univerAPI } = createUniver({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      UniverPresetSheetsCoreEnUS,
      UniverPresetSheetsDrawingEnUS, // [!code ++]
      UniverPresetSheetsAdvancedEnUS, // [!code ++]
    ),
  },
  presets: [
    UniverSheetsCorePreset(),
    UniverSheetsDrawingPreset(), // [!code ++]
    UniverSheetsAdvancedPreset(), // [!code ++]
  ],
})
```

Univer 상용 라이선스가 있다면 [클라이언트에서 라이선스 사용하기](https://docs.univer.ai/ko-KR/server/license.md#in-preset-mode)를 참고하여 설정하세요.

### 프리셋 및 구성

```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
}
```

## Facade API

전체 Facade API 형식 정의는 [FacadeAPI](https://docs.univer.ai/ko-KR/reference/facade.md)에서 확인할 수 있습니다.

### 가져오기

> [!INFO: 플러그인 모드 참고]
> 플러그인 모드에서만 Facade 패키지를 직접 가져와야 합니다. 프리셋 모드에는 해당 Facade 패키지가 이미 포함되어 있으므로 추가로 가져올 필요가 없습니다.

```typescript
import '@univerjs-pro/sheets-pivot/facade'
```

### 피벗 테이블 추가

[`FWorkbook.addPivotTable`](https://docs.univer.ai/ko-KR/reference/facade/workbook.md#addpivottable) 메서드는 피벗 테이블을 추가하며, 성공하면 `FPivotTable` 인스턴스를 반환합니다.

```typescript
// should ensure the sheet range A1:G9 is not empty
const 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 times
let hasAdded = false
// the addPivotTable is async, you can add pivot fields after the pivot table is added
univerAPI.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
  }
})
```

### 피벗 테이블 가져오기

[`FWorkbook.getPivotTableByCell`](https://docs.univer.ai/ko-KR/reference/facade/workbook.md#getpivottablebycell) 메서드는 기준 셀로 피벗 테이블 인스턴스를 가져오며, 대상 셀이 피벗 테이블 안에 있으면 `FPivotTable` 인스턴스를 반환합니다.

```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)
```

[`FPivotTable`](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md) 인스턴스에는 피벗 테이블을 조작할 수 있는 다음 메서드가 있습니다.

| 메서드                                                                                              | 설명                                   |
| ------------------------------------------------------------------------------------------------ | ------------------------------------ |
| [remove](https://docs.univer.ai/ko-KR/reference/facade/generic-pivot-table.md#remove)                                           | 인스턴스에서 피벗 테이블 제거                     |
| [getConfig](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#getconfig)                       | 피벗 테이블 구성, 원본 범위 정보, 기준 셀 정보 및 구성 반환 |
| [addField](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#addfield)                         | 피벗 테이블에 필드 추가                        |
| [removeField](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#removefield)                   | 피벗 테이블에서 필드 제거                       |
| [updateFieldPosition](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#updatefieldposition)   | 피벗 테이블의 필드 위치 업데이트                   |
| [updateValuePosition](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#updatevalueposition)   | ∑값 위치 제어                             |
| [setSubtotalType](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#setsubtotaltype)           | 필드의 부분합 유형 설정                        |
| [setLabelSort](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#setlabelsort)                 | 필드의 레이블 정렬 설정                        |
| [setLabelManualFilter](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#setlabelmanualfilter) | 필드의 레이블 필터 설정                        |
| [renameField](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#renamefield)                   | 필드 이름 변경                             |
| [setValueFilter](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#setvaluefilter)                                   | 값 필터 설정                              |
| [reset](https://docs.univer.ai/ko-KR/reference/facade/generic-pivot-table.md#reset)                                             | 피벗 테이블 필드 초기화                        |
| [setFieldsConfig](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#setfieldsconfig)           | 피벗 테이블 필드 구성 설정                      |
| [getValueFilters](https://docs.univer.ai/ko-KR/reference/facade/pivot-table.md#getvaluefilters)           | 피벗 테이블의 모든 값 필터 가져오기                 |

```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[]
}
```

### 이벤트 리스너

전체 이벤트 형식 정의는 [Events](https://docs.univer.ai/ko-KR/reference/facade/events.md)에서 확인할 수 있습니다.

`univerAPI.Event.BeforePivotTableAdd` 이벤트는 피벗 테이블을 추가하기 전에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableAdded` 이벤트는 피벗 테이블을 추가한 후에 발생합니다.

```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()`
```

`univerAPI.Event.BeforePivotTableMove` 이벤트는 피벗 테이블을 이동하기 전에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableMoved` 이벤트는 피벗 테이블을 이동한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableRendered` 이벤트는 피벗 테이블을 렌더링한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableRemoved` 이벤트는 피벗 테이블을 제거한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldAdded` 이벤트는 피벗 테이블에 필드를 추가한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldRemoved` 이벤트는 피벗 테이블에서 필드를 제거한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldMoved` 이벤트는 피벗 테이블에서 필드를 이동한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldCollapseChanged` 이벤트는 피벗 테이블의 차원을 펼치거나 접은 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldFilterChanged` 이벤트는 피벗 테이블의 차원을 필터링한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldSortChanged` 이벤트는 피벗 테이블의 차원을 정렬한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableFieldSettingChanged` 이벤트는 피벗 테이블의 차원 설정을 변경한 후에 발생합니다.

```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()`
```

`univerAPI.Event.PivotTableValuePositionChanged` 이벤트는 피벗 테이블의 값 위치를 변경한 후에 발생합니다.

```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()`
```

## 값 표시 방식

`setShowDataAs()`로 값 필드를 행, 열 또는 전체 합계의 비율이나 기준 항목과의 차이로 표시할 수 있습니다. 표시 계산만 바뀌며 원본 데이터는 대체되지 않습니다. `getShowDataAs()`는 설정을 읽고 `resetShowDataAs()`는 일반 계산으로 복원합니다.

```ts
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`은 기존 피벗 테이블입니다. 원본 열이나 행 필드가 아닌 값 필드 ID를 사용하세요. 차이 및 누계 모드에는 해당 기준 필드와 기준 항목 설정도 필요합니다.

## 워크시트와 함께 피벗 테이블 복사

피벗 플러그인이 등록되어 있으면 워크시트를 복제할 때 해당 시트의 피벗 테이블과 필드 설정도 복사됩니다. 각 복사본에는 새 피벗 테이블 ID가 부여됩니다. 데이터 원본이 복사한 시트에 있으면 참조가 새 시트를 가리키도록 바뀌고, 다른 시트나 통합 문서에 있으면 기존 참조가 유지됩니다. 복사된 피벗 테이블도 시트 복제 작업과 함께 실행 취소 및 다시 실행됩니다.

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook')

const copiedSheet = workbook.duplicateActiveSheet()
console.log(copiedSheet.getSheetName())
```
