Insert Slicer
Possible Usage Scenarios
A slicer is used to filter data quickly. It can be used to filter data both in a table or pivot table. Microsoft Excel allows you to create slicer by selecting a table or pivot table and then clicking the Insert > Slicer. Aspose.Cells also allows you to create slicer using the Worksheet.Slicers.Add() method.
Create Slicer to a Pivot Table
Please see the following sample code. It 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 and output XLSB format. The following screenshot shows the slicer created by Aspose.Cells in the output Excel file.
Sample Code
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// Load sample Excel file containing pivot table. | |
Workbook wb = new Workbook("sampleCreateSlicerToPivotTable.xlsx"); | |
// Access first worksheet. | |
Worksheet ws = wb.Worksheets[0]; | |
// Access first pivot table inside the worksheet. | |
Aspose.Cells.Pivot.PivotTable pt = ws.PivotTables[0]; | |
// Add slicer relating to pivot table with first base field at cell B22. | |
int idx = ws.Slicers.Add(pt, "B22", pt.BaseFields[0]); | |
// Access the newly added slicer from slicer collection. | |
Aspose.Cells.Slicers.Slicer slicer = ws.Slicers[idx]; | |
// Save the workbook in output XLSX format. | |
wb.Save("outputCreateSlicerToPivotTable.xlsx", SaveFormat.Xlsx); | |
// Save the workbook in output XLSB format. | |
wb.Save("outputCreateSlicerToPivotTable.xlsb", SaveFormat.Xlsb); |
Create Slicer to Excel Table
Please see the following sample code. It loads the sample Excel file that contains a table. It then creates the slicer based on the first column. Finally, it saves the workbook in output XLSX format.
Sample Code
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// Load sample Excel file containing a table. | |
Workbook workbook = new Workbook(sourceDir + "sampleCreateSlicerToExcelTable.xlsx"); | |
// Access first worksheet. | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Access first table inside the worksheet. | |
ListObject table = worksheet.ListObjects[0]; | |
// Add slicer | |
int idx = worksheet.Slicers.Add(table, 0, "H5"); | |
// Save the workbook in output XLSX format. | |
workbook.Save(outputDir + "outputCreateSlicerToExcelTable.xlsx", SaveFormat.Xlsx); |