이 간단한 자습서에서는 환경 구성 및 Python 프로그램 흐름에 대한 정보를 제공하는 자세한 단계를 통해 Python에서 피벗 테이블 만들기를 안내합니다. Python Excel 피벗 테이블을 사용하는 동안 피벗 테이블에 대한 입력 데이터가 포함된 소스 통합 문서를 로드한 후 실행 가능한 샘플 코드를 사용하여 생성됩니다. 결국 결과 통합 문서는 XLSX, XLS 등과 같은 원하는 형식으로 저장됩니다.
Python에서 피벗 테이블을 만드는 단계
- 프로젝트에 Java를 통해 Aspose.Cells for Python 설치 환경 구축
- 피벗 테이블에 대한 입력 데이터가 포함된 Workbook 클래스 개체 로드 또는 생성
- 대상 worksheet에서 피벗 테이블 컬렉션에 대한 참조를 가져옵니다.
- 컬렉션에 피벗 테이블 추가
- 새로 추가된 피벗 테이블 구성
- 피벗 테이블의 각 영역에 원하는 필드 추가
- 피벗 테이블이 있는 출력 통합 문서 저장
이 단계에서는 환경 구성 리소스에 대한 링크와 기능을 달성하기 위해 Python에서 수행할 일련의 작업에 대한 링크를 공유하여 Python 코드가 Excel에서 피벗 테이블을 생성하는 지침을 제공합니다. 요구 사항에 따라 피벗 테이블의 다른 영역에 필드를 추가하도록 안내합니다. 피벗 테이블이 준비되면 원하는 형식으로 Excel 파일에 저장됩니다.
Python으로 Excel 피벗 테이블을 만드는 코드
import jpype | |
import csv | |
import asposecells | |
jpype.startJVM() | |
from asposecells.api import License, Workbook, PivotFieldType, LoadOptions,FileFormatType | |
# Instantiate a license to avoid watermark in the output Excel file having pivot table | |
cellsLicense = License() | |
cellsLicense.setLicense("Aspose.Cells.lic") | |
header = ['City', 'Class', 'Fee'] | |
data = [ | |
['Islamabad','Class 1',750], | |
['Islamabad','Class 4',1000], | |
['Karachi','Class 1',300], | |
['Karachi','Class 4',750], | |
['Karachi','Class 1',2035], | |
['Karachi','Class 4',2500], | |
['Islamabad','Class 1',3215] | |
] | |
with open('data.csv', 'w', encoding='UTF8', newline='') as f: | |
writer = csv.writer(f) | |
# write the header | |
writer.writerow(header) | |
# write the data | |
writer.writerows(data) | |
# Create a CSV LoadOptions class object | |
csvLoadOptions = LoadOptions(FileFormatType.CSV) | |
# Load the CSV data into Workbook class object using the load options | |
csvWorkbook = Workbook("data.csv",csvLoadOptions) | |
# Get access to the first sheet for adding pivot table to it | |
wsPivotTable = csvWorkbook.getWorksheets().get(0) | |
# Get access to pivot tables collection in the selected sheet | |
pivotTablesCollection = wsPivotTable.getPivotTables() | |
# Create the pivot table and save its index | |
pivotTableIndex = pivotTablesCollection.add("=A1:C8", "A10", "PythonPivotTable") | |
# Get access to the newly created pivot table | |
newPivotTable = pivotTablesCollection.get(pivotTableIndex) | |
# set flag to hide grand totals for rows | |
newPivotTable.setRowGrand(False) | |
# Add the first field to the column area of the pivot table | |
newPivotTable.addFieldToArea(PivotFieldType.COLUMN, 0) | |
# Add the second field to the row area of the pivot table | |
newPivotTable.addFieldToArea(PivotFieldType.ROW, 1) | |
# Add the third field to the data area | |
newPivotTable.addFieldToArea(PivotFieldType.DATA, 2) | |
# Saving the Excel file | |
csvWorkbook.save("NewPivotTable.xlsx") | |
jpype.shutdownJVM() |
이 문서에서는 피벗 테이블을 만드는 방법을 안내했습니다. 암호로 보호된 Excel 파일을 읽으려면 다음 문서를 참조하십시오. Python에서 암호로 보호된 Excel 파일 읽기.