Create Slicer to a Pivot Table

Possible Usage Scenarios

Slicers are used to filter data quickly. They can be used to filter data both in a table or pivot table. Microsoft Excel allows you to create a slicer by selecting a table or pivot table and then clicking the Insert > Slicer. Aspose.Cells for Python via Java provides the Worksheet.getSlicers().add() method to create slicer.

Create Slicer to a Pivot Table

The following code snippet loads the sample Excel file that contains the pivot table. It then creates the slicer based on the first base pivot field. Finally, it saves the workbook in output XLSX format. The following screenshot shows the slicer created by Aspose.Cells in the output Excel file.

todo:image_alt_text

Sample Code

import jpype
import asposecells
jpype.startJVM()
from asposecells.api import Workbook, SaveFormat
# Load Source Excel file
workbook = Workbook("sampleCreateSlicerToPivotTable.xlsx")
# Access first worksheet
worksheet = workbook.getWorksheets().get(0)
# Access first pivot table inside the worksheet
pivottable = worksheet.getPivotTables().get(0)
# Add slicer relating to pivot table with first base field at cell B22
idx = worksheet.getSlicers().add(pivottable, "B22", pivottable.getBaseFields().get(0))
# Access the newly added slicer from slicer collection
slicer = worksheet.getSlicers().get(idx)
# Save the workbook in output XLSX format
workbook.save("outputCreateSlicerToPivotTable.xlsx", SaveFormat.XLSX)
jpype.shutdownJVM()