Este breve tutorial direciona para criar tabela dinâmica em Python com a ajuda de etapas detalhadas que fornecem informações sobre a configuração do ambiente e o fluxo do programa Python. Ao usar a tabela dinâmica do Python Excel será criada usando um código de exemplo executável após carregar a pasta de trabalho de origem que contém os dados de entrada para a tabela dinâmica. No final, a pasta de trabalho resultante será salva em qualquer um dos formatos desejados, como XLSX, XLS etc.
Etapas para criar tabela dinâmica em Python
- Estabeleça o ambiente para instalar o Aspose.Cells for Python via Java no projeto
- Carregar ou criar um objeto de classe Workbook contendo dados de entrada para a tabela dinâmica
- Obtenha a referência à coleção de tabelas dinâmicas no destino worksheet
- Adicionar uma tabela dinâmica na coleção
- Configure a tabela dinâmica recém-adicionada
- Adicione os campos desejados nas respectivas áreas da tabela dinâmica
- Salve a pasta de trabalho de saída com a tabela dinâmica nela
Essas etapas fornecem instruções para código Python criar tabela dinâmica no Excel compartilhando um link para o recurso de configuração do ambiente e para uma sequência de tarefas a serem executadas em Python para obter a funcionalidade. Ele orienta a adicionar campos a diferentes áreas na tabela dinâmica conforme o requisito. Uma vez preparada a tabela dinâmica, ela é salva no arquivo Excel no formato desejado.
Código para criar tabela dinâmica do Excel com Python
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() |
Este artigo nos guiou para criar uma tabela dinâmica. Se você quiser ler arquivos do Excel protegidos por senha, consulte o artigo sobre leia o arquivo do Excel protegido por senha em Python.