diff --git a/slicer/add-a-pivot-table-connection-to-the-slicer-for-dynamic-data-filtering.cs b/slicer/add-a-pivot-table-connection-to-the-slicer-for-dynamic-data-filtering.cs new file mode 100644 index 0000000000..9441326c89 --- /dev/null +++ b/slicer/add-a-pivot-table-connection-to-the-slicer-for-dynamic-data-filtering.cs @@ -0,0 +1,51 @@ +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].Value = "Category"; + cells["B1"].Value = "Product"; + cells["C1"].Value = "Sales"; + + cells["A2"].Value = "Electronics"; + cells["B2"].Value = "Laptop"; + cells["C2"].Value = 1200; + + cells["A3"].Value = "Electronics"; + cells["B3"].Value = "Phone"; + cells["C3"].Value = 800; + + cells["A4"].Value = "Furniture"; + cells["B4"].Value = "Chair"; + cells["C4"].Value = 150; + + // Add a pivot table based on the data range + PivotTableCollection pivotTables = sheet.PivotTables; + int pivotIndex = pivotTables.Add("A1:C4", "E1", "SalesPivot"); + PivotTable pivot = pivotTables[pivotIndex]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Row, "Product"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer for the "Category" field (placed at cell F1 -> row 0, column 5) + int slicerIndex = sheet.Slicers.Add(pivot, 0, 5, "Category"); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Connect the slicer to the pivot table for dynamic filtering + slicer.AddPivotConnection(pivot); + + // Save the workbook + workbook.Save("PivotSlicerConnection.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/add-a-slicer-to-a-worksheet-that-contains-a-chart-to-filter-chart-data-dynamically.cs b/slicer/add-a-slicer-to-a-worksheet-that-contains-a-chart-to-filter-chart-data-dynamically.cs new file mode 100644 index 0000000000..d4e1d673fc --- /dev/null +++ b/slicer/add-a-slicer-to-a-worksheet-that-contains-a-chart-to-filter-chart-data-dynamically.cs @@ -0,0 +1,82 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Charts; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerChartDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // ------------------------------------------------- + // 1. Populate sample data (Fruit, Sales) + // ------------------------------------------------- + cells["A1"].PutValue("Fruit"); + cells["B1"].PutValue("Sales"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(120); + cells["A3"].PutValue("Orange"); + cells["B3"].PutValue(150); + cells["A4"].PutValue("Banana"); + cells["B4"].PutValue(90); + cells["A5"].PutValue("Grape"); + cells["B5"].PutValue(60); + + // ------------------------------------------------- + // 2. Create a PivotTable based on the data + // ------------------------------------------------- + // Place the pivot table starting at cell D1 + int pivotIdx = sheet.PivotTables.Add("A1:B5", "D1", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + + // Row field: Fruit, Data field: Sales (Sum) + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + + // Refresh to calculate the pivot data + pivot.RefreshData(); + pivot.CalculateData(); + + // ------------------------------------------------- + // 3. Add a chart that is linked to the PivotTable + // ------------------------------------------------- + // The chart will be placed at rows 12‑22, columns 0‑7 + int chartIdx = sheet.Charts.Add(ChartType.Column, 12, 0, 22, 7); + Chart chart = sheet.Charts[chartIdx]; + chart.Title.Text = "Sales by Fruit (Pivot)"; + + // Use a static address that covers the pivot table data area. + // After the pivot is calculated, the data starts at D2 and ends at E5. + chart.NSeries.Add("D2:E5", true); + chart.NSeries[0].Name = "Sales"; + + // ------------------------------------------------- + // 4. Add a slicer linked to the PivotTable's "Fruit" field + // ------------------------------------------------- + // Place the slicer at cell G1 (row 0, column 6) + int slicerIdx = sheet.Slicers.Add(pivot, 0, 6, "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + slicer.Caption = "Fruit Filter"; + slicer.StyleType = SlicerStyleType.SlicerStyleLight2; + + // ------------------------------------------------- + // 5. Save the workbook + // ------------------------------------------------- + workbook.Save("SlicerChartDemo.xlsx", SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/adjust-slicer-row-height-to-30-points-after-linking-it-to-the-second-table-column.cs b/slicer/adjust-slicer-row-height-to-30-points-after-linking-it-to-the-second-table-column.cs new file mode 100644 index 0000000000..44b6cd2f64 --- /dev/null +++ b/slicer/adjust-slicer-row-height-to-30-points-after-linking-it-to-the-second-table-column.cs @@ -0,0 +1,62 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace AsposeCellsSlicerExample +{ + public class AdjustSlicerRowHeight + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the table + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue("Fruit"); + sheet.Cells["A3"].PutValue("Carrot"); + sheet.Cells["B3"].PutValue("Vegetable"); + sheet.Cells["A4"].PutValue("Banana"); + sheet.Cells["B4"].PutValue("Fruit"); + + // Add a ListObject (table) covering the data range + int tableIndex = sheet.ListObjects.Add("A1", "B4", true); + ListObject table = sheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Add a slicer linked to the second column (Category) of the table + int slicerRow = 6; // zero‑based index (row 7) + int slicerColumn = 0; // column A + int slicerIndex = sheet.Slicers.Add(table, table.ListColumns[1], slicerRow, slicerColumn); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Adjust the slicer row height to 30 points + slicer.RowHeight = 30; + + // Save the workbook + string outputPath = "SlicerRowHeightAdjusted.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Application entry point + public class Program + { + public static void Main(string[] args) + { + AdjustSlicerRowHeight.Run(); + } + } +} \ No newline at end of file diff --git a/slicer/after-adding-new-items-to-a-slicers-cache-call-refresh-and-confirm-the-pivot-table-reflects-the-additions.cs b/slicer/after-adding-new-items-to-a-slicers-cache-call-refresh-and-confirm-the-pivot-table-reflects-the-additions.cs new file mode 100644 index 0000000000..89e371234e --- /dev/null +++ b/slicer/after-adding-new-items-to-a-slicers-cache-call-refresh-and-confirm-the-pivot-table-reflects-the-additions.cs @@ -0,0 +1,88 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsExamples +{ + public class SlicerRefreshDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet (data sheet) + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + Cells cells = dataSheet.Cells; + + // Populate initial source data (Product column and Sales column) + cells["A1"].PutValue("Product"); + cells["B1"].PutValue("Sales"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(100); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(150); + cells["A4"].PutValue("Cherry"); + cells["B4"].PutValue(200); + + // Add a worksheet for the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("Pivot"); + + // Create the pivot table using the source range A1:B4 + int pivotIdx = pivotSheet.PivotTables.Add("A1:B4", "D3", "ProductPivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIdx]; + + // Set row field to Product and data field to Sales + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); + pivotTable.CalculateData(); + + // Add a slicer for the "Product" field on the pivot sheet + int slicerIdx = pivotSheet.Slicers.Add(pivotTable, "F3", "Product"); + Slicer slicer = pivotSheet.Slicers[slicerIdx]; + + // Record the initial number of items in the slicer cache (should be 3) + int initialItemCount = slicer.SlicerCache.SlicerCacheItems.Count; + Console.WriteLine("Initial slicer items count: " + initialItemCount); + + // ----- Add new items to the source data (which the slicer is based on) ----- + // Append new rows below the existing data + cells["A5"].PutValue("Date"); + cells["B5"].PutValue(120); + cells["A6"].PutValue("Elderberry"); + cells["B6"].PutValue(80); + + // Refresh the slicer – this also refreshes the associated pivot table + slicer.Refresh(); + + // Recalculate pivot data to reflect any changes + pivotTable.CalculateData(); + + // Verify that the slicer cache now contains the newly added items + int updatedItemCount = slicer.SlicerCache.SlicerCacheItems.Count; + Console.WriteLine("Updated slicer items count: " + updatedItemCount); + + // Simple confirmation that the pivot table reflects the new items + int pivotRowItemCount = pivotTable.RowFields[0].PivotItems.Count; + Console.WriteLine("Pivot row items count: " + pivotRowItemCount); + + // Save the workbook + workbook.Save("SlicerRefreshDemo.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + SlicerRefreshDemo.Run(); + } + } +} \ No newline at end of file diff --git a/slicer/after-updating-slicer-items-verify-the-associated-pivot-table-reflects-the-new-filter-criteria.cs b/slicer/after-updating-slicer-items-verify-the-associated-pivot-table-reflects-the-new-filter-criteria.cs new file mode 100644 index 0000000000..a3b5630991 --- /dev/null +++ b/slicer/after-updating-slicer-items-verify-the-associated-pivot-table-reflects-the-new-filter-criteria.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerPivotDemo +{ + public class Program + { + public static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate source data (Fruit | Sales) + cells["A1"].PutValue("Fruit"); + cells["B1"].PutValue("Sales"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(120); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(80); + cells["A4"].PutValue("Apple"); + cells["B4"].PutValue(150); + cells["A5"].PutValue("Orange"); + cells["B5"].PutValue(200); + + // Add a pivot table based on the source data + int pivotIdx = sheet.PivotTables.Add("A1:B5", "D3", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); // Row field + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); // Data field (Sum) + + // Refresh data and calculate initial results + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table for the "Fruit" field + int slicerIdx = sheet.Slicers.Add(pivot, "G3", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // ---- Update slicer items: select only "Apple" ---- + for (int i = 0; i < slicer.SlicerCache.SlicerCacheItems.Count; i++) + { + SlicerCacheItem item = slicer.SlicerCache.SlicerCacheItems[i]; + // Select the item if its value is "Apple", otherwise deselect + item.Selected = string.Equals(item.Value, "Apple", StringComparison.OrdinalIgnoreCase); + } + + // Refresh the slicer – this also refreshes and recalculates the linked pivot table + slicer.Refresh(); + + // ---- Verify pivot table reflects the slicer filter ---- + // After the slicer filter, the sum for Apple will be in cell E4 (first data row, second column of the pivot) + double appleSum = 0; + try + { + Cell sumCell = sheet.Cells["E4"]; + if (sumCell.Value != null && double.TryParse(sumCell.Value.ToString(), out double d)) + { + appleSum = d; + } + } + catch (Exception ex) + { + Console.WriteLine($"Failed to read pivot result: {ex.Message}"); + } + + Console.WriteLine($"Sum of Sales for Apple after slicer filter: {appleSum}"); + + // Save the workbook (ensure the path is valid) + string outputPath = "SlicerPivotRefreshDemo.xlsx"; + try + { + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception saveEx) + { + Console.WriteLine($"Failed to save workbook: {saveEx.Message}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/agents.md b/slicer/agents.md new file mode 100644 index 0000000000..103ee108b6 --- /dev/null +++ b/slicer/agents.md @@ -0,0 +1,116 @@ +--- +category: slicer +framework: .NET +parent: ../agents.md +version: v2 +--- + +# Persona + +You are a C# developer specializing in Slicers and interactive filtering using Aspose.Cells for .NET. + +Generate simple, correct, production-quality examples that demonstrate ONE slicer scenario at a time. + +--- + +# Scope + +- Standalone .cs examples +- One operation per example +- Fully runnable with dotnet run +- No external dependencies + +--- + +# Required Namespaces + +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Slicers; + +--- + +# Key APIs + +- Slicer +- SlicerCollection +- ListObject +- Worksheet.Slicers +- SlicerCache + +--- + +# Common Pattern + +1. Create workbook +2. Populate worksheet data +3. Create table or PivotTable +4. Create slicer +5. Configure slicer properties +6. Save workbook +7. Print success message + +--- + +# Slicer Rules + +- Create source data before creating a slicer +- Associate slicers with a valid table or PivotTable +- Use meaningful field names +- One example = one slicer operation + +--- + +# Input Strategy + +- Do NOT rely on external XLSX files +- Create all sample data programmatically +- Keep examples self-contained + +--- + +# Output Rules + +- Always generate output.xlsx +- Ensure workbook is saved successfully +- Output files are written to the working directory + +--- + +# Common Tasks + +- Create slicer +- Access slicers +- Modify slicer properties +- Connect slicer to table data +- Filter data interactively + +--- + +# Common Mistakes + +❌ var workbook = new Workbook(); +✅ Workbook workbook = new Workbook(); + +❌ Create slicer without table or PivotTable source +✅ Create source object before adding slicer + +❌ Workbook workbook = new Workbook("input.xlsx"); +✅ Workbook workbook = new Workbook(); + +--- + +# Code Simplicity + +- Keep examples concise +- Avoid unnecessary abstractions + +--- + +# General Rules + +Refer to the root agents.md for: +- Boundaries +- Testing requirements +- Build and run instructions diff --git a/slicer/apply-a-builtin-slicer-style-such-as-light-1-for-quick-visual-formatting.cs b/slicer/apply-a-builtin-slicer-style-such-as-light-1-for-quick-visual-formatting.cs new file mode 100644 index 0000000000..3d2b409fe8 --- /dev/null +++ b/slicer/apply-a-builtin-slicer-style-such-as-light-1-for-quick-visual-formatting.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +namespace AsposeCellsSlicerStyleDemo +{ + public class Program + { + public static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the pivot table + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Amount"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["B2"].PutValue(100); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["B3"].PutValue(200); + sheet.Cells["A4"].PutValue("C"); + sheet.Cells["B4"].PutValue(300); + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D2", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Category as row field + pivot.AddFieldToArea(PivotFieldType.Data, 1); // Amount as data field + + // Add a slicer linked to the pivot table's first base field (Category) + int slicerIdx = sheet.Slicers.Add(pivot, "F2", 0); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Apply a built‑in slicer style (Light 1) + slicer.StyleType = SlicerStyleType.SlicerStyleLight1; + + // Optional: set additional slicer properties for better visibility + slicer.Caption = "Category Filter"; + slicer.NumberOfColumns = 1; + slicer.WidthPixel = 150; + slicer.HeightPixel = 100; + + // Save the workbook with the styled slicer + workbook.Save("SlicerStyleLight1Demo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/apply-the-slicerstylelight1-formatting-style-to-the-slicer-and-save-changes-in-the-workbook.cs b/slicer/apply-the-slicerstylelight1-formatting-style-to-the-slicer-and-save-changes-in-the-workbook.cs new file mode 100644 index 0000000000..5594e3160d --- /dev/null +++ b/slicer/apply-the-slicerstylelight1-formatting-style-to-the-slicer-and-save-changes-in-the-workbook.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +namespace SlicerStyleDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].Value = "Fruit"; + cells["A2"].Value = "Apple"; + cells["A3"].Value = "Orange"; + cells["A4"].Value = "Banana"; + cells["B1"].Value = "Quantity"; + cells["B2"].Value = 10; + cells["B3"].Value = 15; + cells["B4"].Value = 20; + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "E3", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Fruit field + + // Add a slicer linked to the pivot table + int slicerIdx = sheet.Slicers.Add(pivot, "A1", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Apply the built‑in light style 1 to the slicer + slicer.StyleType = SlicerStyleType.SlicerStyleLight1; + + // Save the workbook with the styled slicer + workbook.Save("SlicerStyleLight1Demo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/arrange-slicer-items-in-multiple-columns-by-setting-the-column-count-property.cs b/slicer/arrange-slicer-items-in-multiple-columns-by-setting-the-column-count-property.cs new file mode 100644 index 0000000000..c7cd22d8b7 --- /dev/null +++ b/slicer/arrange-slicer-items-in-multiple-columns-by-setting-the-column-count-property.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerMultiColumnDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for a pivot table + cells["A1"].Value = "Category"; + cells["B1"].Value = "Product"; + cells["A2"].Value = "Fruits"; + cells["B2"].Value = "Apple"; + cells["A3"].Value = "Fruits"; + cells["B3"].Value = "Banana"; + cells["A4"].Value = "Vegetables"; + cells["B4"].Value = "Carrot"; + + // Add a pivot table based on the data range + int pivotIndex = sheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivotTable = sheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Product"); + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Add a slicer linked to the pivot table field "Category" + // Correct argument order: destination cell name first, then field name + int slicerIndex = sheet.Slicers.Add(pivotTable, "E1", "Category"); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Set slicer properties + slicer.Caption = "Product Categories"; + slicer.TopPixel = 50; + slicer.LeftPixel = 50; + slicer.HeightPixel = 150; + slicer.WidthPixel = 200; + + // Arrange slicer items in multiple columns (e.g., 3 columns) + slicer.NumberOfColumns = 3; + + // Define output file path + string outputPath = "SlicerMultiColumnDemo.xlsx"; + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/batch-create-slicers-for-each-pivot-table-in-a-workbook-using-a-loop-over-all-tables.cs b/slicer/batch-create-slicers-for-each-pivot-table-in-a-workbook-using-a-loop-over-all-tables.cs new file mode 100644 index 0000000000..91e1ec9ba6 --- /dev/null +++ b/slicer/batch-create-slicers-for-each-pivot-table-in-a-workbook-using-a-loop-over-all-tables.cs @@ -0,0 +1,53 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerBatch +{ + class Program + { + static void Main() + { + // Load an existing workbook (replace with your source file) + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through all worksheets in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get the collection of pivot tables on the current worksheet + PivotTableCollection pivots = sheet.PivotTables; + + // Starting position for slicers on this sheet + int slicerRow = 0; + int slicerColumn = 0; + + // Loop through each pivot table + foreach (PivotTable pivot in pivots) + { + // Loop through each base field of the pivot table + foreach (PivotField baseField in pivot.BaseFields) + { + // Add a slicer for the current base field + // Using the overload: Add(PivotTable, int row, int column, PivotField baseField) + int slicerIndex = sheet.Slicers.Add(pivot, slicerRow, slicerColumn, baseField); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Optional: set a caption to identify the slicer + slicer.Caption = $"{pivot.Name}_{baseField.Name}_Slicer"; + + // Move to the next column for the next slicer + slicerColumn += 2; // adjust spacing as needed + } + + // Reset column and move to next row block for the next pivot table + slicerColumn = 0; + slicerRow += 5; // adjust spacing as needed + } + } + + // Save the modified workbook + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/batch-process-multiple-workbooks-adding-slicers-to-each-and-adjusting-their-widths-uniformly.cs b/slicer/batch-process-multiple-workbooks-adding-slicers-to-each-and-adjusting-their-widths-uniformly.cs new file mode 100644 index 0000000000..4193d1a187 --- /dev/null +++ b/slicer/batch-process-multiple-workbooks-adding-slicers-to-each-and-adjusting-their-widths-uniformly.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Slicers; + +namespace BatchSlicerProcessor +{ + class Program + { + static void Main() + { + // Folder containing source workbooks + string sourceFolder = @"C:\InputWorkbooks"; + // Folder where processed workbooks will be saved + string outputFolder = @"C:\OutputWorkbooks"; + + // Ensure output folder exists + Directory.CreateDirectory(outputFolder); + + // Uniform slicer column width (in points) + double uniformColumnWidth = 100.0; + + // Process each .xlsx file in the source folder + foreach (string inputPath in Directory.GetFiles(sourceFolder, "*.xlsx")) + { + // Load existing workbook + Workbook workbook = new Workbook(inputPath); + + // Work with the first worksheet (adjust as needed) + Worksheet worksheet = workbook.Worksheets[0]; + + // ------------------------------------------------- + // Create a simple table if the worksheet has no tables + // (rows 0-4, columns 0-1) – this ensures a data source for the slicer + // ------------------------------------------------- + int tableIndex = worksheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Add a slicer for the first column of the table at cell E1 + int slicerIndex = worksheet.Slicers.Add(table, 0, "E1"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Apply the uniform column width to the slicer + slicer.ColumnWidth = uniformColumnWidth; + + // Save the modified workbook to the output folder + string fileName = Path.GetFileName(inputPath); + string outputPath = Path.Combine(outputFolder, fileName); + workbook.Save(outputPath); + } + } + } +} \ No newline at end of file diff --git a/slicer/before-exporting-to-pdf-set-pdf-conversion-options-to-embed-fonts-and-retain-slicer-formatting.cs b/slicer/before-exporting-to-pdf-set-pdf-conversion-options-to-embed-fonts-and-retain-slicer-formatting.cs new file mode 100644 index 0000000000..7b69ee49f1 --- /dev/null +++ b/slicer/before-exporting-to-pdf-set-pdf-conversion-options-to-embed-fonts-and-retain-slicer-formatting.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); + + // Populate some sample data (optional, just for demonstration) + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Fruits"); + sheet.Cells["A3"].PutValue("Vegetables"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(50); + sheet.Cells["B3"].PutValue(30); + + // Configure PDF conversion options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Embed TrueType fonts in the PDF (required for proper font rendering) + pdfOptions.EmbedStandardWindowsFonts = true; + + // Retain slicer formatting and document structure in the PDF + pdfOptions.ExportDocumentStructure = true; + + // Save the workbook as a PDF using the configured options + workbook.Save("output.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/slicer/before-saving-automatically-select-the-first-item-if-a-slicer-has-no-selected-items.cs b/slicer/before-saving-automatically-select-the-first-item-if-a-slicer-has-no-selected-items.cs new file mode 100644 index 0000000000..430465f85c --- /dev/null +++ b/slicer/before-saving-automatically-select-the-first-item-if-a-slicer-has-no-selected-items.cs @@ -0,0 +1,74 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerAutoSelectDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].PutValue("Fruit"); + cells["A2"].PutValue("Apple"); + cells["A3"].PutValue("Orange"); + cells["A4"].PutValue("Banana"); + cells["B1"].PutValue("Sales"); + cells["B2"].PutValue(100); + cells["B3"].PutValue(200); + cells["B4"].PutValue(300); + + // Add a pivot table based on the data + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Fruit column + pivot.AddFieldToArea(PivotFieldType.Data, 1); // Sales column + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table (field "Fruit") + int slicerIdx = sheet.Slicers.Add(pivot, "F1", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Refresh the slicer to ensure cache is up‑to‑date + slicer.Refresh(); + + // BEFORE saving: ensure each slicer has at least one selected item + foreach (Worksheet ws in workbook.Worksheets) + { + foreach (Slicer s in ws.Slicers) + { + SlicerCacheItemCollection items = s.SlicerCache.SlicerCacheItems; + bool anySelected = false; + + // Check if any item is already selected + for (int i = 0; i < items.Count; i++) + { + if (items[i].Selected) + { + anySelected = true; + break; + } + } + + // If none selected, select the first item + if (!anySelected && items.Count > 0) + { + items[0].Selected = true; + // Optionally set the first visible item index + s.FirstItemIndex = 0; + } + } + } + + // Save the workbook + workbook.Save("SlicerAutoSelectDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/change-the-slicer-layout-direction-to-righttoleft-for-languages-that-read-rtl.cs b/slicer/change-the-slicer-layout-direction-to-righttoleft-for-languages-that-read-rtl.cs new file mode 100644 index 0000000000..588f195a14 --- /dev/null +++ b/slicer/change-the-slicer-layout-direction-to-righttoleft-for-languages-that-read-rtl.cs @@ -0,0 +1,57 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +class SlicerRtlDemo +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Amount"); + cells["A2"].PutValue("Fruit"); + cells["B2"].PutValue(120); + cells["A3"].PutValue("Vegetable"); + cells["B3"].PutValue(80); + cells["A4"].PutValue("Fruit"); + cells["B4"].PutValue(150); + cells["A5"].PutValue("Vegetable"); + cells["B5"].PutValue(200); + + // Add a pivot table based on the data range + int pivotIndex = worksheet.PivotTables.Add("A1:B5", "D2", "PivotTable1"); + PivotTable pivot = worksheet.PivotTables[pivotIndex]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.PivotTableStyleType = PivotTableStyleType.PivotTableStyleMedium9; + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table (Category field) + // Correct parameter order: destination cell name first, then field name + int slicerIndex = worksheet.Slicers.Add(pivot, "E2", "Category"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Change the slicer layout direction to right‑to‑left + slicer.Shape.TextDirection = TextDirectionType.RightToLeft; + + // Optionally set the whole worksheet to display right‑to‑left + worksheet.DisplayRightToLeft = true; + + // Save the workbook + workbook.Save("SlicerRTL.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/slicer/change-the-slicer-title-to-region-filter-and-update-the-workbook-accordingly.cs b/slicer/change-the-slicer-title-to-region-filter-and-update-the-workbook-accordingly.cs new file mode 100644 index 0000000000..c9e14b08a3 --- /dev/null +++ b/slicer/change-the-slicer-title-to-region-filter-and-update-the-workbook-accordingly.cs @@ -0,0 +1,28 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class UpdateSlicerTitle +{ + static void Main() + { + // Load the existing workbook + Workbook workbook = new Workbook("input.xlsx"); + + // Access the first worksheet (adjust if needed) + Worksheet worksheet = workbook.Worksheets[0]; + + // Get the slicer collection from the worksheet + SlicerCollection slicers = worksheet.Slicers; + + // If there is at least one slicer, change its title + if (slicers.Count > 0) + { + Slicer slicer = slicers[0]; + slicer.Title = "Region Filter"; // Set the new title + } + + // Save the updated workbook + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/clear-all-selected-items-in-a-slicer-to-reset-the-filter-to-its-default-state.cs b/slicer/clear-all-selected-items-in-a-slicer-to-reset-the-filter-to-its-default-state.cs new file mode 100644 index 0000000000..bea560bd64 --- /dev/null +++ b/slicer/clear-all-selected-items-in-a-slicer-to-reset-the-filter-to-its-default-state.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerReset +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for a pivot table + cells["A1"].Value = "Category"; + cells["A2"].Value = "A"; + cells["A3"].Value = "B"; + cells["A4"].Value = "C"; + cells["B1"].Value = "Amount"; + cells["B2"].Value = 10; + cells["B3"].Value = 20; + cells["B4"].Value = 30; + + // Add a pivot table based on the data + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table + // Note: The correct parameter order is (pivot, destinationCell, baseFieldName) + SlicerCollection slicers = sheet.Slicers; + int slicerIdx = slicers.Add(pivot, "E1", "Category"); + Slicer slicer = slicers[slicerIdx]; + + // ---- USER FILTER SIMULATION ---- + // Select only the first item to simulate a filtered state + SlicerCacheItemCollection items = slicer.SlicerCache.SlicerCacheItems; + for (int i = 0; i < items.Count; i++) + { + items[i].Selected = i == 0; // only first item selected + } + slicer.Refresh(); + + // ---- CLEAR ALL SELECTIONS (RESET FILTER) ---- + // To reset the slicer, select all items (equivalent to "Clear Filter") + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + item.Selected = true; // select every item + } + slicer.Refresh(); + + // Save the workbook + string outputPath = "SlicerResetDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/clone-an-existing-slicer-and-place-the-copy-on-another-worksheet-for-parallel-filtering.cs b/slicer/clone-an-existing-slicer-and-place-the-copy-on-another-worksheet-for-parallel-filtering.cs new file mode 100644 index 0000000000..7fab1738ca --- /dev/null +++ b/slicer/clone-an-existing-slicer-and-place-the-copy-on-another-worksheet-for-parallel-filtering.cs @@ -0,0 +1,71 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class CloneSlicerExample +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // ----------------------------------------------------------------- + // Source worksheet: contains data, pivot table and the original slicer + // ----------------------------------------------------------------- + Worksheet sourceSheet = workbook.Worksheets[0]; + sourceSheet.Name = "Source"; + + // Populate sample data + sourceSheet.Cells["A1"].PutValue("Fruit"); + sourceSheet.Cells["B1"].PutValue("Sales"); + sourceSheet.Cells["A2"].PutValue("Apple"); + sourceSheet.Cells["B2"].PutValue(100); + sourceSheet.Cells["A3"].PutValue("Orange"); + sourceSheet.Cells["B3"].PutValue(150); + sourceSheet.Cells["A4"].PutValue("Banana"); + sourceSheet.Cells["B4"].PutValue(200); + + // Create a pivot table based on the data + int pivotIndex = sourceSheet.PivotTables.Add("A1:B4", "D2", "Pivot1"); + PivotTable pivot = sourceSheet.PivotTables[pivotIndex]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + pivot.PivotTableStyleType = PivotTableStyleType.PivotTableStyleMedium9; + pivot.RefreshData(); + pivot.CalculateData(); + + // Add the original slicer on the source sheet + int originalSlicerIndex = sourceSheet.Slicers.Add(pivot, "F2", "Fruit"); + Slicer originalSlicer = sourceSheet.Slicers[originalSlicerIndex]; + originalSlicer.Caption = "Fruit Filter"; + originalSlicer.StyleType = SlicerStyleType.SlicerStyleLight2; + originalSlicer.NumberOfColumns = 1; + originalSlicer.WidthPixel = 150; + originalSlicer.HeightPixel = 200; + + // --------------------------------------------------------------- + // Destination worksheet: will host the cloned slicer for parallel use + // --------------------------------------------------------------- + Worksheet destSheet = workbook.Worksheets.Add("Clone"); + + // Add a slicer on the destination sheet using the same pivot table and field + int clonedSlicerIndex = destSheet.Slicers.Add(pivot, "F2", "Fruit"); + Slicer clonedSlicer = destSheet.Slicers[clonedSlicerIndex]; + + // Copy visual and behavioral properties from the original slicer + clonedSlicer.Caption = originalSlicer.Caption; + clonedSlicer.StyleType = originalSlicer.StyleType; + clonedSlicer.NumberOfColumns = originalSlicer.NumberOfColumns; + clonedSlicer.WidthPixel = originalSlicer.WidthPixel; + clonedSlicer.HeightPixel = originalSlicer.HeightPixel; + clonedSlicer.LockedPosition = originalSlicer.LockedPosition; + clonedSlicer.ShowCaption = originalSlicer.ShowCaption; + + // Ensure the cloned slicer is synchronized with its pivot table + clonedSlicer.Refresh(); + + // Save the workbook + workbook.Save("ClonedSlicerDemo.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/compare-slicer-selection-states-before-and-after-calling-refresh-to-ensure-changes-are-applied-correctly.cs b/slicer/compare-slicer-selection-states-before-and-after-calling-refresh-to-ensure-changes-are-applied-correctly.cs new file mode 100644 index 0000000000..f031d583a7 --- /dev/null +++ b/slicer/compare-slicer-selection-states-before-and-after-calling-refresh-to-ensure-changes-are-applied-correctly.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerRefreshComparison +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + dataSheet.Cells["A1"].PutValue("Category"); + dataSheet.Cells["A2"].PutValue("A"); + dataSheet.Cells["A3"].PutValue("B"); + dataSheet.Cells["A4"].PutValue("C"); + dataSheet.Cells["B1"].PutValue("Value"); + dataSheet.Cells["B2"].PutValue(10); + dataSheet.Cells["B3"].PutValue(20); + dataSheet.Cells["B4"].PutValue(30); + + // Add a pivot table based on the data + int pivotIdx = dataSheet.PivotTables.Add("A1:B4", "D1", "Pivot1"); + PivotTable pivot = dataSheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); + pivot.AddFieldToArea(PivotFieldType.Data, 1); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table + int slicerIdx = dataSheet.Slicers.Add(pivot, "F1", "Category"); + Slicer slicer = dataSheet.Slicers[slicerIdx]; + slicer.StyleType = SlicerStyleType.SlicerStyleLight1; + + // Ensure initial selection: select first item, deselect others + for (int i = 0; i < slicer.SlicerCache.SlicerCacheItems.Count; i++) + { + slicer.SlicerCache.SlicerCacheItems[i].Selected = i == 0; + } + + // Capture selection states before refresh + List beforeRefresh = new List(); + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + beforeRefresh.Add(item.Selected); + } + + // Modify underlying data: add a new category that will appear in the slicer + dataSheet.Cells["A5"].PutValue("D"); + dataSheet.Cells["B5"].PutValue(40); + + // Refresh the slicer (also refreshes the pivot table) + slicer.Refresh(); + + // Capture selection states after refresh + List afterRefresh = new List(); + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + afterRefresh.Add(item.Selected); + } + + // Compare and output differences + Console.WriteLine("Comparison of slicer selection states before and after Refresh:"); + int count = Math.Max(beforeRefresh.Count, afterRefresh.Count); + for (int i = 0; i < count; i++) + { + string itemValue = i < slicer.SlicerCache.SlicerCacheItems.Count + ? slicer.SlicerCache.SlicerCacheItems[i].Value + : $"Item{i}"; + bool before = i < beforeRefresh.Count ? beforeRefresh[i] : false; + bool after = i < afterRefresh.Count ? afterRefresh[i] : false; + Console.WriteLine($"Item '{itemValue}': before={before}, after={after}"); + } + + // Save the workbook + workbook.Save("SlicerRefreshComparison.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/configure-the-slicer-to-display-items-with-no-data-by-toggling-the-showzeroitems-option.cs b/slicer/configure-the-slicer-to-display-items-with-no-data-by-toggling-the-showzeroitems-option.cs new file mode 100644 index 0000000000..e39bfb6a56 --- /dev/null +++ b/slicer/configure-the-slicer-to-display-items-with-no-data-by-toggling-the-showzeroitems-option.cs @@ -0,0 +1,42 @@ +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class ConfigureSlicerShowZeroItems +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["A4"].PutValue("C"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["B4"].PutValue(30); + + // Add a pivot table based on the data range + int pivotIndex = worksheet.PivotTables.Add("A1:B4", "E3", "PivotTable1"); + PivotTable pivotTable = worksheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Category field + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Value field + + // Add a slicer linked to the pivot table for the "Category" field + int slicerIndex = worksheet.Slicers.Add(pivotTable, "A1", "Category"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Enable showing all items, even those without data + slicer.ShowAllItems = true; + + // Configure how items with no data are displayed (e.g., natural order) + slicer.ShowTypeOfItemsWithNoData = ItemsWithNoDataShowMode.Natural; + + // Save the workbook + workbook.Save("SlicerShowZeroItems.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/convert-the-workbook-with-slicers-to-pdf-while-preserving-slicer-appearance-and-metadata.cs b/slicer/convert-the-workbook-with-slicers-to-pdf-while-preserving-slicer-appearance-and-metadata.cs new file mode 100644 index 0000000000..a6795ff882 --- /dev/null +++ b/slicer/convert-the-workbook-with-slicers-to-pdf-while-preserving-slicer-appearance-and-metadata.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class ConvertWorkbookWithSlicersToPdf +{ + static void Main() + { + const string inputPath = "InputWithSlicers.xlsx"; + const string outputPath = "OutputWithSlicers.pdf"; + + try + { + // Verify the input file exists before loading + if (!File.Exists(inputPath)) + throw new FileNotFoundException($"Input file not found: {inputPath}"); + + // Load the workbook containing slicers + Workbook workbook = new Workbook(inputPath); + + // Ensure all slicers are printable so they appear in the PDF + foreach (Worksheet sheet in workbook.Worksheets) + { + foreach (Slicer slicer in sheet.Slicers) + { + slicer.IsPrintable = true; + } + } + + // Configure PDF save options (retain document structure) + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + ExportDocumentStructure = true + }; + + // Save the workbook as PDF + workbook.Save(outputPath, pdfOptions); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/slicer/create-a-batch-process-that-removes-a-named-slicer-from-multiple-xlsx-workbooks-and-saves-each-as-pdf.cs b/slicer/create-a-batch-process-that-removes-a-named-slicer-from-multiple-xlsx-workbooks-and-saves-each-as-pdf.cs new file mode 100644 index 0000000000..dc28ceb73b --- /dev/null +++ b/slicer/create-a-batch-process-that-removes-a-named-slicer-from-multiple-xlsx-workbooks-and-saves-each-as-pdf.cs @@ -0,0 +1,92 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Utility; + +namespace BatchSlicerRemovalApp +{ + class BatchSlicerRemoval + { + static void Main() + { + // Folder containing the source XLSX workbooks + string sourceFolder = @"C:\Input"; + // Folder where the resulting PDFs will be saved + string outputFolder = @"C:\Output"; + // Name of the slicer to be removed from each workbook + string slicerNameToRemove = "FruitSlicer1"; + + try + { + // Verify source folder exists + if (!Directory.Exists(sourceFolder)) + { + Console.WriteLine($"Source folder not found: {sourceFolder}"); + return; + } + + // Ensure output folder exists + Directory.CreateDirectory(outputFolder); + + // Process each XLSX file in the source folder + foreach (string xlsxPath in Directory.GetFiles(sourceFolder, "*.xlsx")) + { + // Verify the file exists before loading + if (!File.Exists(xlsxPath)) + { + Console.WriteLine($"File not found (skipped): {xlsxPath}"); + continue; + } + + try + { + // Load the workbook + Workbook workbook = new Workbook(xlsxPath); + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get the slicer collection for the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Iterate backwards for safe removal + for (int i = slicers.Count - 1; i >= 0; i--) + { + Slicer slicer = slicers[i]; + if (slicer.Name == slicerNameToRemove) + { + slicers.Remove(slicer); + } + } + } + + // Save the modified workbook to a temporary file + string tempXlsxPath = Path.Combine(outputFolder, + Path.GetFileNameWithoutExtension(xlsxPath) + "_temp.xlsx"); + workbook.Save(tempXlsxPath, SaveFormat.Xlsx); + + // Convert the temporary XLSX file to PDF + string pdfPath = Path.Combine(outputFolder, + Path.GetFileNameWithoutExtension(xlsxPath) + ".pdf"); + ConversionUtility.Convert(tempXlsxPath, pdfPath); + + // Delete the temporary file + if (File.Exists(tempXlsxPath)) + { + File.Delete(tempXlsxPath); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error processing file '{xlsxPath}': {ex.Message}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/create-a-function-returning-true-if-a-slicer-contains-any-selected-items-otherwise-false.cs b/slicer/create-a-function-returning-true-if-a-slicer-contains-any-selected-items-otherwise-false.cs new file mode 100644 index 0000000000..a527dce6b2 --- /dev/null +++ b/slicer/create-a-function-returning-true-if-a-slicer-contains-any-selected-items-otherwise-false.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace SlicerUtilities +{ + public static class SlicerHelper + { + /// + /// Returns true if the specified slicer has at least one selected item. + /// + public static bool HasSelectedItems(Slicer slicer) + { + if (slicer == null) throw new ArgumentNullException(nameof(slicer)); + + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + if (item.Selected) + return true; + } + + return false; + } + + /// + /// Demonstrates loading a workbook and checking slicer selections. + /// + public static void Demo() + { + const string filePath = "InputWithSlicer.xlsx"; + + // Prevent FileNotFoundException + if (!File.Exists(filePath)) + { + Console.WriteLine($"File not found: {filePath}"); + return; + } + + try + { + // Load workbook + Workbook workbook = new Workbook(filePath); + + // Ensure a slicer exists on the first worksheet + if (workbook.Worksheets[0].Slicers.Count == 0) + { + Console.WriteLine("No slicers found on the first worksheet."); + return; + } + + // Get the first slicer + Slicer slicer = workbook.Worksheets[0].Slicers[0]; + + // Check for selected items + bool anySelected = HasSelectedItems(slicer); + Console.WriteLine($"Slicer '{slicer.Name}' has selected items: {anySelected}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error processing workbook: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + try + { + SlicerHelper.Demo(); + } + catch (Exception ex) + { + Console.WriteLine($"Unhandled exception: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/create-a-slicer-and-retrieve-its-identifier-for-use-in-subsequent-api-calls.cs b/slicer/create-a-slicer-and-retrieve-its-identifier-for-use-in-subsequent-api-calls.cs new file mode 100644 index 0000000000..3950699d6a --- /dev/null +++ b/slicer/create-a-slicer-and-retrieve-its-identifier-for-use-in-subsequent-api-calls.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the pivot table + sheet.Cells["A1"].PutValue("Fruit"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["A4"].PutValue("Banana"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["B4"].PutValue(15); + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + // Use the first field (Fruit) as a row field + pivot.AddFieldToArea(PivotFieldType.Row, 0); + + // Access the slicer collection of the worksheet + SlicerCollection slicers = sheet.Slicers; + + // Add a slicer linked to the pivot table, placed at cell E1, filtering by the "Fruit" field + int slicerIdx = slicers.Add(pivot, "E1", "Fruit"); + + // Retrieve the slicer object using the returned index + Slicer slicer = slicers[slicerIdx]; + + // Optionally set a custom name for easier reference later + slicer.Name = "FruitSlicer"; + + // Output the slicer identifier (index) and name + Console.WriteLine($"Slicer Index: {slicerIdx}"); + Console.WriteLine($"Slicer Name: {slicer.Name}"); + + // Save the workbook (optional, demonstrates full lifecycle) + workbook.Save("SlicerDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/create-a-slicer-linked-to-a-pivot-table-within-the-loaded-workbook.cs b/slicer/create-a-slicer-linked-to-a-pivot-table-within-the-loaded-workbook.cs new file mode 100644 index 0000000000..45a64496f5 --- /dev/null +++ b/slicer/create-a-slicer-linked-to-a-pivot-table-within-the-loaded-workbook.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class SlicerLinkedToPivot +{ + static void Main() + { + // Load an existing workbook that already contains a pivot table + Workbook workbook = new Workbook("input.xlsx"); + + // Assume the pivot table is on the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Retrieve the first pivot table in the worksheet + if (sheet.PivotTables.Count == 0) + { + Console.WriteLine("No pivot tables found in the worksheet."); + return; + } + PivotTable pivot = sheet.PivotTables[0]; + + // Add a slicer linked to the pivot table. + // The slicer will be placed with its upper‑left corner at cell E2 + // and will filter by the pivot field named "fruit". + int slicerIndex = sheet.Slicers.Add(pivot, "E2", "fruit"); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Optional: set a caption and style for the slicer + slicer.Caption = "Fruit Slicer"; + slicer.StyleType = SlicerStyleType.SlicerStyleLight2; + + // Save the modified workbook + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/create-a-slicer-linked-to-a-table-column-then-set-its-placement-to-the-topright-corner.cs b/slicer/create-a-slicer-linked-to-a-table-column-then-set-its-placement-to-the-topright-corner.cs new file mode 100644 index 0000000000..4357894844 --- /dev/null +++ b/slicer/create-a-slicer-linked-to-a-table-column-then-set-its-placement-to-the-topright-corner.cs @@ -0,0 +1,61 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; +using Aspose.Cells.Drawing; + +namespace SlicerPlacementExample +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the table (two columns: Category and Value) + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["A4"].PutValue("A"); + sheet.Cells["B4"].PutValue(30); + sheet.Cells["A5"].PutValue("C"); + sheet.Cells["B5"].PutValue(40); + + // Add a ListObject (table) that covers the data range A1:B5 + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Add a slicer linked to the first column ("Category") of the table. + // The slicer will be placed starting at row 7, column 5 (cell E7). + SlicerCollection slicers = sheet.Slicers; + int slicerIndex = slicers.Add(table, table.ListColumns[0], 6, 4); // zero‑based indices + Slicer slicer = slicers[slicerIndex]; + + // Set the slicer title (optional) + slicer.Title = "Category Filter"; + + // Set the placement so the slicer moves and resizes with the cells. + // This uses the obsolete Placement property as required. + slicer.Placement = PlacementType.MoveAndSize; + + // Position the slicer at the top‑right corner of the worksheet. + // TopPixel = 0 places it at the top; LeftPixel is set to a large value + // to push it towards the right edge (adjust as needed for your sheet size). + slicer.TopPixel = 0; + slicer.LeftPixel = 800; // approximate right‑most position + + // Optionally adjust size + slicer.WidthPixel = 150; + slicer.HeightPixel = 200; + + // Save the workbook + workbook.Save("SlicerTopRightPlacement.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/create-a-slicer-then-copy-its-properties-to-a-new-slicer-on-another-worksheet.cs b/slicer/create-a-slicer-then-copy-its-properties-to-a-new-slicer-on-another-worksheet.cs new file mode 100644 index 0000000000..46c8400990 --- /dev/null +++ b/slicer/create-a-slicer-then-copy-its-properties-to-a-new-slicer-on-another-worksheet.cs @@ -0,0 +1,72 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +class SlicerCopyExample +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet1 = workbook.Worksheets[0]; + Cells cells = sheet1.Cells; + + // Populate sample data for a pivot table + cells["A1"].Value = "Fruit"; + cells["A2"].Value = "Apple"; + cells["A3"].Value = "Orange"; + cells["A4"].Value = "Banana"; + cells["B1"].Value = "Quantity"; + cells["B2"].Value = 10; + cells["B3"].Value = 20; + cells["B4"].Value = 30; + + // Add a pivot table on the first sheet + int pivotIdx = sheet1.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivot = sheet1.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Quantity"); + + // Add a slicer on the first sheet linked to the pivot table + int slicerIdx1 = sheet1.Slicers.Add(pivot, "E2", "Fruit"); + Slicer slicer1 = sheet1.Slicers[slicerIdx1]; + + // Set various properties on the original slicer + slicer1.Caption = "Fruit Selector"; + slicer1.StyleType = SlicerStyleType.SlicerStyleDark2; + slicer1.NumberOfColumns = 2; + slicer1.WidthPixel = 200; + slicer1.HeightPixel = 120; + slicer1.LockedPosition = true; + slicer1.ShowCaption = true; + + // Position the slicer using its shape + slicer1.Shape.Left = 100; + slicer1.Shape.Top = 50; + + // Add a second worksheet + Worksheet sheet2 = workbook.Worksheets.Add("Sheet2"); + + // Add a slicer on the second sheet linked to the same pivot table + int slicerIdx2 = sheet2.Slicers.Add(pivot, "E2", "Fruit"); + Slicer slicer2 = sheet2.Slicers[slicerIdx2]; + + // Copy properties from slicer1 to slicer2 + slicer2.Caption = slicer1.Caption; + slicer2.StyleType = slicer1.StyleType; + slicer2.NumberOfColumns = slicer1.NumberOfColumns; + slicer2.WidthPixel = slicer1.WidthPixel; + slicer2.HeightPixel = slicer1.HeightPixel; + slicer2.LockedPosition = slicer1.LockedPosition; + slicer2.ShowCaption = slicer1.ShowCaption; + + // Copy shape positioning + slicer2.Shape.Left = slicer1.Shape.Left; + slicer2.Shape.Top = slicer1.Shape.Top; + + // Save the workbook + workbook.Save("SlicerCopyExample.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/delete-a-slicer-by-name-from-the-workbook-to-clean-up-unused-controls.cs b/slicer/delete-a-slicer-by-name-from-the-workbook-to-clean-up-unused-controls.cs new file mode 100644 index 0000000000..10b483b104 --- /dev/null +++ b/slicer/delete-a-slicer-by-name-from-the-workbook-to-clean-up-unused-controls.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +class DeleteSlicerByName +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate some data and create a table to attach a slicer to + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["A4"].PutValue("A"); + int tableIdx = sheet.ListObjects.Add("A1", "A4", true); + ListObject table = sheet.ListObjects[tableIdx]; + + // Add a slicer and give it a distinct name + int slicerIdx = sheet.Slicers.Add(table, 0, "C1"); + Slicer slicer = sheet.Slicers[slicerIdx]; + slicer.Name = "TargetSlicer"; + + // Retrieve the slicer by its name and remove it from the collection + SlicerCollection slicers = sheet.Slicers; + Slicer slicerToRemove = slicers["TargetSlicer"]; // indexer by name + slicers.Remove(slicerToRemove); // delete the slicer + + // Save the workbook + workbook.Save("DeletedSlicer.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/export-a-workbook-containing-slicers-to-pdf-ensuring-all-slicers-appear-on-the-same-page.cs b/slicer/export-a-workbook-containing-slicers-to-pdf-ensuring-all-slicers-appear-on-the-same-page.cs new file mode 100644 index 0000000000..9f888c065f --- /dev/null +++ b/slicer/export-a-workbook-containing-slicers-to-pdf-ensuring-all-slicers-appear-on-the-same-page.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // For ListObject +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; // For PdfSaveOptions + +namespace SlicerPdfExport +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a table + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["A4"].PutValue("A"); + sheet.Cells["B4"].PutValue(30); + sheet.Cells["A5"].PutValue("C"); + sheet.Cells["B5"].PutValue(40); + + // Add a table that covers the data range (A1:B5) + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "DataTable"; // Friendly name + + // Add a slicer linked to the first column of the table (Category) + // Position the slicer at D2 (row 1, column 3) + int slicerIndex = sheet.Slicers.Add(table, table.ListColumns[0], 1, 3); + Slicer slicer = sheet.Slicers[slicerIndex]; + slicer.Shape.IsPrintable = true; // Ensure slicer appears in PDF + + // Configure PDF save options to fit all content on a single page + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + OnePagePerSheet = true, + AllColumnsInOnePagePerSheet = true + }; + + // Define output file path and ensure directory exists + string outputPath = "SlicersExport.pdf"; + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook as PDF; slicer will appear on the same page as the data + workbook.Save(outputPath, pdfOptions); + Console.WriteLine($"PDF saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/export-the-slicer-as-an-image-and-embed-it-in-a-pdf-report-generated-from-the-workbook.cs b/slicer/export-the-slicer-as-an-image-and-embed-it-in-a-pdf-report-generated-from-the-workbook.cs new file mode 100644 index 0000000000..4e9e16daef --- /dev/null +++ b/slicer/export-the-slicer-as-an-image-and-embed-it-in-a-pdf-report-generated-from-the-workbook.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +namespace SlicerToPdfReport +{ + class Program + { + static void Main() + { + // 1. Create a workbook and add sample data + Workbook sourceWb = new Workbook(); + Worksheet sourceWs = sourceWb.Worksheets[0]; + sourceWs.Cells["A1"].PutValue("Category"); + sourceWs.Cells["A2"].PutValue("Fruit"); + sourceWs.Cells["A3"].PutValue("Vegetable"); + sourceWs.Cells["B1"].PutValue("Amount"); + sourceWs.Cells["B2"].PutValue(120); + sourceWs.Cells["B3"].PutValue(80); + + // 2. Create a pivot table based on the data + int pivotIdx = sourceWs.PivotTables.Add("A1:B3", "D1", "PivotTable1"); + PivotTable pivot = sourceWs.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Category as row field + pivot.AddFieldToArea(PivotFieldType.Data, 1); // Amount as data field + + // 3. Add a slicer linked to the pivot table (field index 0 = Category) + int slicerIdx = sourceWs.Slicers.Add(pivot, 20, 2, 0); + Slicer slicer = sourceWs.Slicers[slicerIdx]; + slicer.IsPrintable = true; // ensure it appears in rendered image + + // 4. Render the worksheet (including the slicer) to an image stream + ImageOrPrintOptions imgOptions = new ImageOrPrintOptions + { + ImageType = ImageType.Png, + OnePagePerSheet = true + }; + SheetRender sheetRender = new SheetRender(sourceWs, imgOptions); + using (MemoryStream slicerImageStream = new MemoryStream()) + { + // Render first (and only) page to the stream + sheetRender.ToImage(0, slicerImageStream); + slicerImageStream.Position = 0; // reset for reading + + // 5. Create a new workbook that will serve as the PDF report + Workbook reportWb = new Workbook(); + Worksheet reportWs = reportWb.Worksheets[0]; + reportWs.Name = "Report"; + + // 6. Insert the slicer image into the report worksheet + // Place the image at cell A1 (row 0, column 0) + reportWs.Pictures.Add(0, 0, slicerImageStream); + + // 7. Save the report workbook as PDF + reportWb.Save("SlicerReport.pdf", SaveFormat.Pdf); + } + + // Clean up renderers + sheetRender.Dispose(); + } + } +} \ No newline at end of file diff --git a/slicer/export-the-workbook-containing-slicers-to-pdf-and-compare-slicer-positions-with-the-original-excel-file.cs b/slicer/export-the-workbook-containing-slicers-to-pdf-and-compare-slicer-positions-with-the-original-excel-file.cs new file mode 100644 index 0000000000..cc4a06e74d --- /dev/null +++ b/slicer/export-the-workbook-containing-slicers-to-pdf-and-compare-slicer-positions-with-the-original-excel-file.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; + +class ExportSlicersToPdf +{ + static void Main() + { + // Load the workbook that contains slicers + string excelPath = "SlicersDemo.xlsx"; + Workbook workbook = new Workbook(excelPath); + + // Collect slicer position information from the original workbook + var slicerInfo = new List(); + foreach (Worksheet ws in workbook.Worksheets) + { + foreach (Slicer slicer in ws.Slicers) + { + // Access the shape associated with the slicer + var shape = slicer.Shape; + + // Record basic position and size properties + slicerInfo.Add( + $"Worksheet: {ws.Name}, Slicer: {slicer.Name}, " + + $"Top={shape.Top}, Left={shape.Left}, " + + $"Width={shape.Width}, Height={shape.Height}"); + } + } + + // Save the workbook to PDF, exporting the document structure + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.ExportDocumentStructure = true; // retain document structure in PDF + workbook.Save("SlicersOutput.pdf", pdfOptions); + + // Output the collected slicer positions for comparison + Console.WriteLine("Slicer positions in the original Excel file:"); + foreach (string info in slicerInfo) + { + Console.WriteLine(info); + } + } +} \ No newline at end of file diff --git a/slicer/export-the-workbook-to-pdf-with-high-resolution-to-ensure-slicer-text-remains-sharp.cs b/slicer/export-the-workbook-to-pdf-with-high-resolution-to-ensure-slicer-text-remains-sharp.cs new file mode 100644 index 0000000000..10129954e6 --- /dev/null +++ b/slicer/export-the-workbook-to-pdf-with-high-resolution-to-ensure-slicer-text-remains-sharp.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Rendering; + +namespace AsposeCellsHighResPdfExport +{ + class Program + { + static void Main() + { + try + { + // Set a high DPI for rendering to improve image and shape quality. + CellsHelper.DPI = 300; + + // Create a new workbook and obtain the first worksheet. + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data. + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Fruits"); + sheet.Cells["A3"].PutValue("Vegetables"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(50); + sheet.Cells["B3"].PutValue(30); + + // Add a simple column chart. + int chartIndex = sheet.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B3", true); + chart.NSeries.CategoryData = "A2:A3"; + chart.Title.Text = "Sample Chart"; + + // Configure PDF save options for high quality. + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + OptimizationType = PdfOptimizationType.Standard, + ExportDocumentStructure = true, + DefaultFont = "Arial", + EmbedStandardWindowsFonts = true + }; + pdfOptions.SetImageResample(300, 90); // Resample images to 300 DPI with JPEG quality 90. + + // Define output path and ensure its directory exists. + string outputPath = "HighResolutionOutput.pdf"; + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook as a PDF. + workbook.Save(outputPath, pdfOptions); + + Console.WriteLine($"Workbook successfully saved to PDF with high resolution at: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/generate-a-pdf-report-that-includes-only-the-slicer-region-by-setting-the-worksheets-print-area.cs b/slicer/generate-a-pdf-report-that-includes-only-the-slicer-region-by-setting-the-worksheets-print-area.cs new file mode 100644 index 0000000000..d74d670e51 --- /dev/null +++ b/slicer/generate-a-pdf-report-that-includes-only-the-slicer-region-by-setting-the-worksheets-print-area.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // For ListObject +using Aspose.Cells.Pivot; // For PivotTable +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; + +class SlicerPdfReport +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Name = "Data"; + + // Populate sample data that the slicer will be linked to + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["A4"].PutValue("C"); + worksheet.Cells["B4"].PutValue(30); + + // Create a table (ListObject) from the data range + int tableIdx = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIdx]; + // Use DisplayName to set the table name (Name property not available in some versions) + table.DisplayName = "DataTable"; + + // Add a pivot table based on the created table + int pivotIdx = worksheet.PivotTables.Add("DataTable", "D5", "PivotTable1"); + PivotTable pivot = worksheet.PivotTables[pivotIdx]; + + // Add a slicer linked to the "Category" field of the pivot table + int slicerIdx = worksheet.Slicers.Add(pivot, "Category", "CategorySlicer"); + Slicer slicer = worksheet.Slicers[slicerIdx]; + + // Make the slicer printable + slicer.Shape.IsPrintable = true; + + // Define a print area that includes the slicer (adjust as needed) + string slicerRange = "C5:F10"; + worksheet.PageSetup.PrintArea = slicerRange; + + // Save the workbook as PDF; only the defined print area will be exported + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + string outputPath = "SlicerReport.pdf"; + + // Ensure we can write the file (overwrite if it exists) + if (File.Exists(outputPath)) + File.Delete(outputPath); + + workbook.Save(outputPath, pdfOptions); + Console.WriteLine($"PDF report generated successfully: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/slicer/generate-a-report-listing-each-slicers-title-size-and-linked-table-column-for-auditing-purposes.cs b/slicer/generate-a-report-listing-each-slicers-title-size-and-linked-table-column-for-auditing-purposes.cs new file mode 100644 index 0000000000..9187b5de34 --- /dev/null +++ b/slicer/generate-a-report-listing-each-slicers-title-size-and-linked-table-column-for-auditing-purposes.cs @@ -0,0 +1,60 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class SlicerAuditReport +{ + static void Main() + { + // Load the workbook that contains slicers + Workbook workbook = new Workbook("input.xlsx"); + + // Add a new worksheet to hold the audit report + int reportSheetIndex = workbook.Worksheets.Add(); + Worksheet reportSheet = workbook.Worksheets[reportSheetIndex]; + reportSheet.Name = "SlicerReport"; + + // Write header row + reportSheet.Cells["A1"].PutValue("Worksheet"); + reportSheet.Cells["B1"].PutValue("Slicer Name"); + reportSheet.Cells["C1"].PutValue("Caption"); + reportSheet.Cells["D1"].PutValue("Width (px)"); + reportSheet.Cells["E1"].PutValue("Height (px)"); + reportSheet.Cells["F1"].PutValue("Linked Source"); + + int currentRow = 1; // zero‑based index for the next data row + + // Iterate through all worksheets (except the report sheet itself) + foreach (Worksheet ws in workbook.Worksheets) + { + if (ws.Name == "SlicerReport") + continue; + + SlicerCollection slicers = ws.Slicers; + + // Process each slicer on the worksheet + for (int i = 0; i < slicers.Count; i++) + { + Slicer slicer = slicers[i]; + + // Worksheet name + reportSheet.Cells[currentRow, 0].PutValue(ws.Name); + // Slicer object name + reportSheet.Cells[currentRow, 1].PutValue(slicer.Name); + // Caption (used as the title) + reportSheet.Cells[currentRow, 2].PutValue(slicer.Caption); + // Size in pixels + reportSheet.Cells[currentRow, 3].PutValue(slicer.WidthPixel); + reportSheet.Cells[currentRow, 4].PutValue(slicer.HeightPixel); + // Linked source (table or pivot field name) + string linkedSource = slicer.SlicerCache != null ? slicer.SlicerCache.SourceName : string.Empty; + reportSheet.Cells[currentRow, 5].PutValue(linkedSource); + + currentRow++; + } + } + + // Save the workbook with the added report sheet + workbook.Save("SlicerReport.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/hide-the-slicer-header-row-to-create-a-compact-filtering-control-without-a-title.cs b/slicer/hide-the-slicer-header-row-to-create-a-compact-filtering-control-without-a-title.cs new file mode 100644 index 0000000000..baa1b3bab6 --- /dev/null +++ b/slicer/hide-the-slicer-header-row-to-create-a-compact-filtering-control-without-a-title.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerHeaderHideDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].Value = "Category"; + cells["B1"].Value = "Amount"; + cells["A2"].Value = "Fruit"; + cells["B2"].Value = 120; + cells["A3"].Value = "Vegetable"; + cells["B3"].Value = 80; + cells["A4"].Value = "Grain"; + cells["B4"].Value = 150; + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D5", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table + int slicerIdx = sheet.Slicers.Add(pivot, "F5", "Category"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Hide the slicer header (caption) to make it compact + slicer.ShowCaption = false; + + // Optional: adjust appearance + slicer.StyleType = SlicerStyleType.SlicerStyleLight1; + slicer.NumberOfColumns = 1; + + // Save the workbook + workbook.Save("SlicerHeaderHidden.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/identify-slicers-starting-with-region-remove-them-and-save-the-workbook-in-xlsx-format.cs b/slicer/identify-slicers-starting-with-region-remove-them-and-save-the-workbook-in-xlsx-format.cs new file mode 100644 index 0000000000..12da9f5b09 --- /dev/null +++ b/slicer/identify-slicers-starting-with-region-remove-them-and-save-the-workbook-in-xlsx-format.cs @@ -0,0 +1,40 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerRemoval +{ + class Program + { + static void Main() + { + // Load the workbook (replace with your actual file path) + string inputPath = "input.xlsx"; + Workbook workbook = new Workbook(inputPath); + + // Iterate through all worksheets in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get the slicer collection for the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Loop backwards to safely remove items while iterating + for (int i = slicers.Count - 1; i >= 0; i--) + { + Slicer slicer = slicers[i]; + + // Check if the slicer's name starts with "Region" + if (!string.IsNullOrEmpty(slicer.Name) && slicer.Name.StartsWith("Region", StringComparison.OrdinalIgnoreCase)) + { + // Remove the slicer at the current index + slicers.RemoveAt(i); + } + } + } + + // Save the modified workbook in XLSX format + string outputPath = "output.xlsx"; + workbook.Save(outputPath, SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/slicer/implement-error-handling-when-adding-a-slicer-to-a-nonexistent-table-column-in-the-worksheet.cs b/slicer/implement-error-handling-when-adding-a-slicer-to-a-nonexistent-table-column-in-the-worksheet.cs new file mode 100644 index 0000000000..f84aeffa72 --- /dev/null +++ b/slicer/implement-error-handling-when-adding-a-slicer-to-a-nonexistent-table-column-in-the-worksheet.cs @@ -0,0 +1,63 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace AsposeCellsSlicerErrorHandling +{ + public class Program + { + public static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for a table (2 columns) + worksheet.Cells["A1"].PutValue("Column1"); + worksheet.Cells["B1"].PutValue("Column2"); + worksheet.Cells["A2"].PutValue("Data1"); + worksheet.Cells["B2"].PutValue("Data2"); + worksheet.Cells["A3"].PutValue("Data3"); + worksheet.Cells["B3"].PutValue("Data4"); + + // Add a ListObject (table) covering the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Attempt to add a slicer for a column that does NOT exist (e.g., index 5) + int nonExistentColumnIndex = 5; // zero‑based index, out of range for this table + + try + { + // Validate that the requested column index exists + if (nonExistentColumnIndex < 0 || nonExistentColumnIndex >= table.ListColumns.Count) + { + throw new ArgumentOutOfRangeException( + nameof(nonExistentColumnIndex), + $"Column index {nonExistentColumnIndex} is out of range. Table has {table.ListColumns.Count} columns."); + } + + // If validation passes, retrieve the ListColumn and add the slicer + ListColumn listColumn = table.ListColumns[nonExistentColumnIndex]; + SlicerCollection slicers = worksheet.Slicers; + // Add slicer at position row 1, column 3 (cell D1) + slicers.Add(table, listColumn, 1, 3); + Console.WriteLine("Slicer added successfully."); + } + catch (ArgumentOutOfRangeException ex) + { + // Handle the specific case where the column does not exist + Console.WriteLine($"Error adding slicer: {ex.Message}"); + } + catch (Exception ex) + { + // General exception handling for any other unexpected errors + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + + // Save the workbook (lifecycle rule) + workbook.Save("SlicerErrorHandlingOutput.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/iterate-all-worksheets-delete-every-slicer-and-export-the-modified-workbook-to-pdf.cs b/slicer/iterate-all-worksheets-delete-every-slicer-and-export-the-modified-workbook-to-pdf.cs new file mode 100644 index 0000000000..4e2821ba9e --- /dev/null +++ b/slicer/iterate-all-worksheets-delete-every-slicer-and-export-the-modified-workbook-to-pdf.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSlicerRemoval +{ + class Program + { + static void Main(string[] args) + { + // Load an existing workbook (replace the path with your file) + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through all worksheets in the workbook + foreach (Worksheet worksheet in workbook.Worksheets) + { + // Get the slicer collection for the current worksheet + SlicerCollection slicers = worksheet.Slicers; + + // Remove slicers starting from the last index to avoid shifting issues + for (int i = slicers.Count - 1; i >= 0; i--) + { + slicers.RemoveAt(i); + } + } + + // Prepare PDF save options (default options are sufficient) + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Save the modified workbook as a PDF file + workbook.Save("output.pdf", pdfOptions); + } + } +} \ No newline at end of file diff --git a/slicer/iterate-each-slicer-log-its-selected-items-then-deselect-all-items-and-refresh.cs b/slicer/iterate-each-slicer-log-its-selected-items-then-deselect-all-items-and-refresh.cs new file mode 100644 index 0000000000..8cd6f1a79d --- /dev/null +++ b/slicer/iterate-each-slicer-log-its-selected-items-then-deselect-all-items-and-refresh.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerDemo +{ + public class SlicerSelectionHandler + { + public static void Run() + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Verify input file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file \"{inputPath}\" not found."); + return; + } + + try + { + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get slicers on the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Process each slicer + for (int s = 0; s < slicers.Count; s++) + { + Slicer slicer = slicers[s]; + + // Access slicer cache items + SlicerCacheItemCollection items = slicer.SlicerCache.SlicerCacheItems; + + // Log currently selected items + Console.WriteLine($"Worksheet: {sheet.Name}, Slicer: {slicer.Name}"); + for (int i = 0; i < items.Count; i++) + { + SlicerCacheItem item = items[i]; + if (item.Selected) + { + Console.WriteLine($" Selected Item: {item.Value}"); + } + } + + // Deselect all items + for (int i = 0; i < items.Count; i++) + { + items[i].Selected = false; + } + + // Refresh slicer to apply changes + slicer.Refresh(); + } + } + + // Save the modified workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to \"{outputPath}\"."); + } + catch (Exception ex) + { + // Handle any runtime errors + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + SlicerSelectionHandler.Run(); + } + } +} \ No newline at end of file diff --git a/slicer/iterate-over-slicercacheitems-to-deselect-items-matching-a-specific-keyword.cs b/slicer/iterate-over-slicercacheitems-to-deselect-items-matching-a-specific-keyword.cs new file mode 100644 index 0000000000..0e4a2e27ef --- /dev/null +++ b/slicer/iterate-over-slicercacheitems-to-deselect-items-matching-a-specific-keyword.cs @@ -0,0 +1,50 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerDemo +{ + class DeselectSlicerItemsByKeyword + { + static void Main() + { + // Load an existing workbook that contains a slicer + Workbook workbook = new Workbook("input.xlsx"); + // Ensure all worksheets are refreshed (required for slicer data) + workbook.Worksheets.RefreshAll(); + + // Define the keyword for which slicer items should be deselected + string keyword = "Apple"; + + // Iterate through all worksheets to find slicers + foreach (Worksheet sheet in workbook.Worksheets) + { + // If the worksheet has no slicers, continue to next sheet + if (sheet.Slicers.Count == 0) continue; + + // Process each slicer in the worksheet + foreach (Slicer slicer in sheet.Slicers) + { + // Access the collection of slicer cache items + SlicerCacheItemCollection cacheItems = slicer.SlicerCache.SlicerCacheItems; + + // Iterate over each cache item + foreach (SlicerCacheItem item in cacheItems) + { + // Deselect the item if its value contains the specified keyword + if (item.Value != null && item.Value.Contains(keyword, StringComparison.OrdinalIgnoreCase)) + { + item.Selected = false; + } + } + + // Refresh the slicer to apply the selection changes + slicer.Refresh(); + } + } + + // Save the modified workbook + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/iterate-through-all-slicers-in-the-workbook-and-set-each-printable-flag-to-false.cs b/slicer/iterate-through-all-slicers-in-the-workbook-and-set-each-printable-flag-to-false.cs new file mode 100644 index 0000000000..dabd5bd33c --- /dev/null +++ b/slicer/iterate-through-all-slicers-in-the-workbook-and-set-each-printable-flag-to-false.cs @@ -0,0 +1,28 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class Program +{ + static void Main() + { + // Load the workbook from a file + Workbook workbook = new Workbook("input.xlsx"); + + // Loop through all worksheets in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + // Access the slicer collection of the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Set the IsPrintable property of each slicer to false + foreach (Slicer slicer in slicers) + { + slicer.IsPrintable = false; + } + } + + // Save the modified workbook to a new file + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/list-all-slicer-names-on-a-worksheet-and-write-them-to-a-text-file.cs b/slicer/list-all-slicer-names-on-a-worksheet-and-write-them-to-a-text-file.cs new file mode 100644 index 0000000000..d49b120e18 --- /dev/null +++ b/slicer/list-all-slicer-names-on-a-worksheet-and-write-them-to-a-text-file.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class ListSlicerNames +{ + static void Main() + { + // Load an existing workbook (replace with your file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Get the first worksheet (or specify the desired one) + Worksheet worksheet = workbook.Worksheets[0]; + + // Access the slicer collection on the worksheet + SlicerCollection slicers = worksheet.Slicers; + + // Collect slicer names + List slicerNames = new List(); + for (int i = 0; i < slicers.Count; i++) + { + slicerNames.Add(slicers[i].Name); + } + + // Write the slicer names to a text file + File.WriteAllLines("SlicerNames.txt", slicerNames); + + // Optionally save the workbook if any changes were made + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/load-a-workbook-create-slicers-for-multiple-table-columns-and-align-them-vertically-with-equal-spacing.cs b/slicer/load-a-workbook-create-slicers-for-multiple-table-columns-and-align-them-vertically-with-equal-spacing.cs new file mode 100644 index 0000000000..e7810cfb59 --- /dev/null +++ b/slicer/load-a-workbook-create-slicers-for-multiple-table-columns-and-align-them-vertically-with-equal-spacing.cs @@ -0,0 +1,71 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace SlicerAlignmentDemo +{ + class Program + { + static void Main() + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure there is at least one table; if not, create a simple sample table + if (sheet.ListObjects.Count == 0) + { + // Sample data + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["A4"].PutValue("A"); + sheet.Cells["B4"].PutValue(30); + + // Add the table covering the sample range + int tableIdx = sheet.ListObjects.Add("A1", "B4", true); + // Optional: apply a style + sheet.ListObjects[tableIdx].TableStyleType = TableStyleType.TableStyleMedium2; + } + + // Reference the first table on the worksheet + ListObject table = sheet.ListObjects[0]; + + // Get the slicer collection for the worksheet + SlicerCollection slicers = sheet.Slicers; + + // Configuration for vertical alignment + int startRow = 5; // Row index for the first slicer (0‑based) + int startColumn = 5; // Column index for all slicers (0‑based) + int slicerHeight = 150; // Height of each slicer in pixels + int slicerWidth = 200; // Width of each slicer in pixels + int verticalSpacing = 10; // Space between slicers in pixels + + // Create a slicer for each column of the table and align them vertically + for (int i = 0; i < table.ListColumns.Count; i++) + { + // Add slicer using the overload that accepts ListObject, ListColumn, row, column + int slicerIdx = slicers.Add(table, table.ListColumns[i], startRow, startColumn); + Slicer slicer = slicers[slicerIdx]; + + // Set size + slicer.HeightPixel = slicerHeight; + slicer.WidthPixel = slicerWidth; + + // Position slicer vertically with equal spacing + slicer.TopPixel = i * (slicerHeight + verticalSpacing); + slicer.LeftPixel = 50; // Fixed left offset for all slicers + + // Optional: give each slicer a meaningful name + slicer.Name = $"Slicer_{table.ListColumns[i].Name}"; + } + + // Save the modified workbook (replace with your desired output path) + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/load-a-workbook-from-a-memory-stream-update-slicer-selections-refresh-pivot-tables-and-write-pdf-to-stream.cs b/slicer/load-a-workbook-from-a-memory-stream-update-slicer-selections-refresh-pivot-tables-and-write-pdf-to-stream.cs new file mode 100644 index 0000000000..795734340a --- /dev/null +++ b/slicer/load-a-workbook-from-a-memory-stream-update-slicer-selections-refresh-pivot-tables-and-write-pdf-to-stream.cs @@ -0,0 +1,102 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace AsposeCellsDemo +{ + public class Program + { + static void Main(string[] args) + { + // Paths for input Excel file and output PDF file + string inputPath = "input.xlsx"; + string outputPath = "output.pdf"; + + // Verify that the input file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + try + { + // Load the Excel file into a memory stream + using (FileStream fileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) + using (MemoryStream excelStream = new MemoryStream()) + { + fileStream.CopyTo(excelStream); + + // Convert to PDF with slicer and pivot table refresh + MemoryStream pdfStream = WorkbookProcessor.ConvertToPdfWithRefresh(excelStream); + if (pdfStream == null) + { + Console.WriteLine("Conversion failed."); + return; + } + + // Save the resulting PDF to disk + using (FileStream outStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + pdfStream.CopyTo(outStream); + } + + Console.WriteLine($"PDF successfully saved to: {outputPath}"); + } + } + catch (Exception ex) + { + // Catch any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class WorkbookProcessor + { + /// + /// Loads an Excel workbook from the provided memory stream, refreshes all slicers and pivot tables, + /// and returns the workbook saved as a PDF in a new memory stream. + /// + /// MemoryStream containing the source Excel file. + /// MemoryStream containing the PDF representation of the workbook, or null if an error occurs. + public static MemoryStream ConvertToPdfWithRefresh(MemoryStream excelStream) + { + try + { + // Ensure the input stream is positioned at the beginning + excelStream.Position = 0; + + // Load the workbook from the stream + Workbook workbook = new Workbook(excelStream); + + // Refresh all slicers in all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + for (int i = 0; i < sheet.Slicers.Count; i++) + { + Slicer slicer = sheet.Slicers[i]; + slicer.Refresh(); // Refresh slicer and its underlying pivot tables + } + } + + // Refresh all pivot tables in the workbook + workbook.Worksheets.RefreshPivotTables(); + + // Save the refreshed workbook as PDF into a new memory stream + MemoryStream pdfStream = new MemoryStream(); + workbook.Save(pdfStream, SaveFormat.Pdf); + pdfStream.Position = 0; // Reset position for reading + + return pdfStream; + } + catch (Exception ex) + { + // Log the exception (could be replaced with proper logging) + Console.WriteLine($"Conversion error: {ex.Message}"); + return null; + } + } + } +} \ No newline at end of file diff --git a/slicer/load-a-workbook-from-an-excel-file-into-memory-for-further-manipulation.cs b/slicer/load-a-workbook-from-an-excel-file-into-memory-for-further-manipulation.cs new file mode 100644 index 0000000000..27d8e2948e --- /dev/null +++ b/slicer/load-a-workbook-from-an-excel-file-into-memory-for-further-manipulation.cs @@ -0,0 +1,28 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsLoadExample +{ + class Program + { + static void Main(string[] args) + { + // Path to the Excel file to be loaded + string excelFilePath = "input.xlsx"; + + // Load the workbook into memory using the Workbook(string) constructor + Workbook workbook = new Workbook(excelFilePath); + + // The workbook is now in memory and can be manipulated. + // Example: read the value of cell A1 from the first worksheet + Worksheet firstSheet = workbook.Worksheets[0]; + string cellValue = firstSheet.Cells["A1"].StringValue; + Console.WriteLine($"Value of A1: {cellValue}"); + + // Additional manipulation can be performed here... + + // (Optional) Save the workbook after modifications + // workbook.Save("output.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/slicer/load-an-xlsx-workbook-create-a-slicer-for-a-table-column-and-save-the-file.cs b/slicer/load-an-xlsx-workbook-create-a-slicer-for-a-table-column-and-save-the-file.cs new file mode 100644 index 0000000000..f348279dac --- /dev/null +++ b/slicer/load-an-xlsx-workbook-create-a-slicer-for-a-table-column-and-save-the-file.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Slicers; + +class Program +{ + static void Main() + { + try + { + const string inputPath = "Input.xlsx"; + const string outputPath = "Output.xlsx"; + + // Load existing workbook or create a new one if the file is missing + Workbook workbook; + if (File.Exists(inputPath)) + { + workbook = new Workbook(inputPath); + } + else + { + workbook = new Workbook(); + workbook.Worksheets[0].Name = "Sheet1"; + } + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure there is at least one table (ListObject) in the worksheet + if (sheet.ListObjects.Count == 0) + { + // Create sample data for a table + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["A4"].PutValue("A"); + sheet.Cells["B4"].PutValue(30); + + // Add a table covering the range A1:B4 (firstRow, firstColumn, totalRows-1, totalColumns-1) + int tableIdx = sheet.ListObjects.Add(0, 0, 3, 1, true); + // No explicit Refresh method needed; the table is ready after creation + } + + // Retrieve the first table in the worksheet + ListObject table = sheet.ListObjects[0]; + + // Add a slicer for the first column of the table and place it at cell E2 + int slicerIdx = sheet.Slicers.Add(table, 0, "E2"); + Slicer slicer = sheet.Slicers[slicerIdx]; + slicer.Caption = "Category Slicer"; + + // Save the modified workbook + workbook.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/slicer/load-an-xlsx-workbook-remove-a-named-slicer-and-save-the-workbook-as-xlsx.cs b/slicer/load-an-xlsx-workbook-remove-a-named-slicer-and-save-the-workbook-as-xlsx.cs new file mode 100644 index 0000000000..24339c86fe --- /dev/null +++ b/slicer/load-an-xlsx-workbook-remove-a-named-slicer-and-save-the-workbook-as-xlsx.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class RemoveSlicerDemo +{ + static void Main() + { + // Load the existing XLSX workbook + Workbook workbook = new Workbook("input.xlsx"); + + // The name of the slicer that should be removed + string slicerNameToRemove = "FruitSlicer1"; + + // Search each worksheet for the slicer with the specified name + foreach (Worksheet sheet in workbook.Worksheets) + { + SlicerCollection slicers = sheet.Slicers; + + for (int i = 0; i < slicers.Count; i++) + { + Slicer slicer = slicers[i]; + + // Slicer.Name holds the slicer's name + if (slicer.Name == slicerNameToRemove) + { + // Remove the slicer from the collection + slicers.Remove(slicer); + // Exit the loops after removal + break; + } + } + } + + // Save the modified workbook as XLSX + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/load-multiple-workbooks-remove-all-slicers-and-archive-the-resulting-pdfs-in-a-zip-file.cs b/slicer/load-multiple-workbooks-remove-all-slicers-and-archive-the-resulting-pdfs-in-a-zip-file.cs new file mode 100644 index 0000000000..ae66308bb1 --- /dev/null +++ b/slicer/load-multiple-workbooks-remove-all-slicers-and-archive-the-resulting-pdfs-in-a-zip-file.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; // for PdfSaveOptions if needed + +class Program +{ + static void Main() + { + // List of Excel files to process + List excelFiles = new List + { + "Book1.xlsx", + "Book2.xlsx", + "Book3.xlsx" + }; + + // Temporary folder for generated PDFs + string pdfFolder = Path.Combine(Path.GetTempPath(), "AsposePdfOutput"); + Directory.CreateDirectory(pdfFolder); + + // Process each workbook + foreach (string excelPath in excelFiles) + { + // Load workbook (uses Workbook(string) constructor rule) + Workbook wb = new Workbook(excelPath); + + // Remove all slicers from every worksheet + foreach (Worksheet ws in wb.Worksheets) + { + SlicerCollection slicers = ws.Slicers; + // Remove slicers while collection is not empty + while (slicers.Count > 0) + { + // Delete slicer at index 0 (uses SlicerCollection.RemoveAt rule) + slicers.RemoveAt(0); + } + } + + // Prepare PDF file name + string pdfFileName = Path.GetFileNameWithoutExtension(excelPath) + ".pdf"; + string pdfPath = Path.Combine(pdfFolder, pdfFileName); + + // Save workbook as PDF (uses Workbook.Save(string, SaveFormat) rule) + wb.Save(pdfPath, SaveFormat.Pdf); + + // Release resources + wb.Dispose(); + } + + // Create a zip archive containing all PDFs + string zipPath = "AllWorkbooks.pdf.zip"; + if (File.Exists(zipPath)) + File.Delete(zipPath); + + using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create)) + using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)) + { + foreach (string pdfFile in Directory.GetFiles(pdfFolder, "*.pdf")) + { + // Add each PDF to the zip (free‑form code, no specific rule) + archive.CreateEntryFromFile(pdfFile, Path.GetFileName(pdfFile)); + } + } + + // Clean up temporary PDF files + Directory.Delete(pdfFolder, true); + + Console.WriteLine("All workbooks have been converted to PDF, slicers removed, and archived to: " + zipPath); + } +} \ No newline at end of file diff --git a/slicer/load-workbooks-in-parallel-threads-remove-a-designated-slicer-from-each-and-save-results-as-pdfs.cs b/slicer/load-workbooks-in-parallel-threads-remove-a-designated-slicer-from-each-and-save-results-as-pdfs.cs new file mode 100644 index 0000000000..f61af4e755 --- /dev/null +++ b/slicer/load-workbooks-in-parallel-threads-remove-a-designated-slicer-from-each-and-save-results-as-pdfs.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Aspose.Cells; +using Aspose.Cells.Slicers; // SlicerCollection resides in this namespace +using Aspose.Cells.Rendering; + +namespace AsposeCellsParallelSlicerRemoval +{ + class Program + { + static void Main() + { + try + { + // Input workbook files (adjust paths as needed) + string[] inputFiles = new string[] + { + @"C:\Input\Workbook1.xlsx", + @"C:\Input\Workbook2.xlsx", + @"C:\Input\Workbook3.xlsx" + }; + + // Output PDF files (same name, different folder) + string outputFolder = @"C:\Output\"; + Directory.CreateDirectory(outputFolder); + + // Prepare tasks for parallel processing + List tasks = new List(); + foreach (string inputPath in inputFiles) + { + // Verify source file exists before scheduling the task + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Source file not found: {inputPath}"); + continue; + } + + string fileNameWithoutExt = Path.GetFileNameWithoutExtension(inputPath); + string outputPath = Path.Combine(outputFolder, fileNameWithoutExt + ".pdf"); + + tasks.Add(Task.Run(() => ProcessWorkbook(inputPath, outputPath))); + } + + // Wait for all tasks to complete + Task.WaitAll(tasks.ToArray()); + + Console.WriteLine("All workbooks processed."); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + + /// + /// Loads a workbook, removes the first slicer from each worksheet (if any), + /// and saves the result as a PDF. + /// + /// Path to the source Excel file. + /// Path where the PDF will be saved. + static void ProcessWorkbook(string inputPath, string outputPath) + { + try + { + // Load the workbook from file + Workbook workbook = new Workbook(inputPath); + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Access the slicer collection of the worksheet + SlicerCollection slicers = sheet.Slicers; + + // If there is at least one slicer, remove the first one + if (slicers != null && slicers.Count > 0) + { + slicers.RemoveAt(0); + } + } + + // Prepare PDF save options (default options are sufficient) + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Save the modified workbook as PDF + workbook.Save(outputPath, pdfOptions); + } + catch (FileNotFoundException fnfEx) + { + Console.WriteLine($"File not found: {fnfEx.FileName}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error processing '{inputPath}': {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/lock-a-slicer-to-prevent-end-users-from-modifying-its-configuration-on-protected-sheets.cs b/slicer/lock-a-slicer-to-prevent-end-users-from-modifying-its-configuration-on-protected-sheets.cs new file mode 100644 index 0000000000..9fc0609bbb --- /dev/null +++ b/slicer/lock-a-slicer-to-prevent-end-users-from-modifying-its-configuration-on-protected-sheets.cs @@ -0,0 +1,38 @@ +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +class LockSlicerDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the table + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["A4"].PutValue("A"); + worksheet.Cells["A5"].PutValue("B"); + + // Create a table from the data range + int tableIndex = worksheet.ListObjects.Add("A1", "A5", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Add a slicer linked to the first column of the table + int slicerIndex = worksheet.Slicers.Add(table, 0, "C1"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Lock the slicer so its configuration cannot be changed when the sheet is protected + slicer.IsLocked = true; // Locks the slicer shape (obsolete but functional) + slicer.LockedPosition = true; // Prevents moving or resizing the slicer + + // Protect the worksheet with all protection options + worksheet.Protect(ProtectionType.All, "password123", null); + + // Save the workbook + workbook.Save("LockedSlicerDemo.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/mark-the-slicer-as-nonprintable-and-ensure-it-does-not-appear-in-printed-output.cs b/slicer/mark-the-slicer-as-nonprintable-and-ensure-it-does-not-appear-in-printed-output.cs new file mode 100644 index 0000000000..9cad93bf73 --- /dev/null +++ b/slicer/mark-the-slicer-as-nonprintable-and-ensure-it-does-not-appear-in-printed-output.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +namespace AsposeCellsSlicerNonPrintableDemo +{ + public class Program + { + public static void Main() + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + sheet.Cells["A1"].Value = "Category"; + sheet.Cells["A2"].Value = "A"; + sheet.Cells["A3"].Value = "B"; + sheet.Cells["A4"].Value = "C"; + + sheet.Cells["B1"].Value = "Amount"; + sheet.Cells["B2"].Value = 100; + sheet.Cells["B3"].Value = 150; + sheet.Cells["B4"].Value = 200; + + // Add a pivot table based on the data + PivotTableCollection pivots = sheet.PivotTables; + int pivotIdx = pivots.Add("A1:B4", "D1", "Pivot1"); + PivotTable pivot = pivots[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table + SlicerCollection slicers = sheet.Slicers; + int slicerIdx = slicers.Add(pivot, "F1", "Category"); + Slicer slicer = slicers[slicerIdx]; + + // Mark the slicer as non‑printable using the underlying Shape object + // (Slicer.IsPrintable is obsolete; Shape.IsPrintable is the recommended property) + slicer.Shape.IsPrintable = false; + + // Save the workbook (lifecycle: save) + workbook.Save("SlicerNonPrintableDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/modify-the-slicer-font-family-size-and-color-to-enhance-label-readability.cs b/slicer/modify-the-slicer-font-family-size-and-color-to-enhance-label-readability.cs new file mode 100644 index 0000000000..b1d29c6bdf --- /dev/null +++ b/slicer/modify-the-slicer-font-family-size-and-color-to-enhance-label-readability.cs @@ -0,0 +1,56 @@ +using System.Drawing; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +namespace AsposeCellsSlicerFontDemo +{ + public class Program + { + public static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for the pivot table + sheet.Cells["A1"].Value = "Fruit"; + sheet.Cells["A2"].Value = "Apple"; + sheet.Cells["A3"].Value = "Orange"; + sheet.Cells["A4"].Value = "Banana"; + sheet.Cells["B1"].Value = "Quantity"; + sheet.Cells["B2"].Value = 10; + sheet.Cells["B3"].Value = 15; + sheet.Cells["B4"].Value = 20; + + // Add a pivot table based on the sample data + int pivotIdx = sheet.PivotTables.Add("A1:B4", "E1", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Row field: Fruit + pivot.AddFieldToArea(PivotFieldType.Data, 1); // Data field: Quantity + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table + int slicerIdx = sheet.Slicers.Add(pivot, "G1", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Modify slicer font for better readability + // Access the underlying shape of the slicer + SlicerShape slicerShape = slicer.Shape as SlicerShape; + if (slicerShape != null) + { + // Set desired font family, size, and color + slicerShape.Font.Name = "Calibri"; + slicerShape.Font.Size = 12; + slicerShape.Font.Color = Color.DarkBlue; + // Optionally make the font bold + slicerShape.Font.IsBold = true; + } + + // Save the workbook with the customized slicer + workbook.Save("SlicerFontDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/move-the-slicer-to-cell-d5-and-align-it-with-existing-chart-objects.cs b/slicer/move-the-slicer-to-cell-d5-and-align-it-with-existing-chart-objects.cs new file mode 100644 index 0000000000..4c6916baf9 --- /dev/null +++ b/slicer/move-the-slicer-to-cell-d5-and-align-it-with-existing-chart-objects.cs @@ -0,0 +1,63 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +class MoveSlicerAndAlignChart +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // ---------- Sample data ---------- + sheet.Cells["A1"].Value = "Fruit"; + sheet.Cells["A2"].Value = "Apple"; + sheet.Cells["A3"].Value = "Orange"; + sheet.Cells["A4"].Value = "Banana"; + + sheet.Cells["B1"].Value = "Sales"; + sheet.Cells["B2"].Value = 120; + sheet.Cells["B3"].Value = 150; + sheet.Cells["B4"].Value = 200; + + // ---------- Create a pivot table ---------- + int pivotIdx = sheet.PivotTables.Add("A1:B4", "E1", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + pivot.RefreshData(); + pivot.CalculateData(); + + // ---------- Add a chart (for demonstration) ---------- + int chartIdx = sheet.Charts.Add(ChartType.Column, 10, 0, 20, 5); + Chart chart = sheet.Charts[chartIdx]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + + // ---------- Add a slicer linked to the pivot ---------- + int slicerIdx = sheet.Slicers.Add(pivot, "A6", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // ---------- Move slicer to cell D5 ---------- + // D5 => row index 4 (zero‑based), column index 3 (zero‑based) + // Use the Shape object of the slicer to set its upper‑left cell position + slicer.Shape.UpperLeftRow = 4; // Row 5 in Excel + slicer.Shape.UpperLeftColumn = 3; // Column D in Excel + + // ---------- Align the existing chart with the slicer ---------- + // Keep the chart size unchanged, only move its top‑left corner to D5 + // Retrieve current size of the chart + int currentBottomRow = chart.ChartObject.LowerRightRow; + int currentRightColumn = chart.ChartObject.LowerRightColumn; + + // Move the chart so its upper‑left corner matches the slicer's position + chart.Move(4, 3, currentBottomRow, currentRightColumn); + + // ---------- Save the workbook ---------- + workbook.Save("SlicerAndChartAligned.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/position-the-slicer-by-specifying-precise-top-and-left-coordinates-programmatically.cs b/slicer/position-the-slicer-by-specifying-precise-top-and-left-coordinates-programmatically.cs new file mode 100644 index 0000000000..4a830ea634 --- /dev/null +++ b/slicer/position-the-slicer-by-specifying-precise-top-and-left-coordinates-programmatically.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +namespace SlicerPositionExample +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate worksheet with sample data for a pivot table + sheet.Cells["A1"].Value = "Category"; + sheet.Cells["B1"].Value = "Sales"; + sheet.Cells["A2"].Value = "Food"; + sheet.Cells["B2"].Value = 1200; + sheet.Cells["A3"].Value = "Beverage"; + sheet.Cells["B3"].Value = 800; + sheet.Cells["A4"].Value = "Electronics"; + sheet.Cells["B4"].Value = 1500; + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D2", "SalesPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + + // Add a slicer linked to the pivot table for the "Category" field + // Destination cell "F2" is the upper‑left corner of the slicer range + int slicerIdx = sheet.Slicers.Add(pivot, "F2", "Category"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Position the slicer precisely using the Shape object (pixel units) + // Set the left offset (horizontal) to 100 pixels from the worksheet's left edge + slicer.Shape.Left = 100; + // Set the top offset (vertical) to 50 pixels from the worksheet's top edge + slicer.Shape.Top = 50; + + // Optionally, adjust size if needed + slicer.Shape.Width = 200; // width in pixels + slicer.Shape.Height = 150; // height in pixels + + // Save the workbook + workbook.Save("SlicerPositioned.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/process-a-list-of-slicer-names-removing-each-one-and-logging-the-operation-result.cs b/slicer/process-a-list-of-slicer-names-removing-each-one-and-logging-the-operation-result.cs new file mode 100644 index 0000000000..052973373a --- /dev/null +++ b/slicer/process-a-list-of-slicer-names-removing-each-one-and-logging-the-operation-result.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + worksheet.Cells["A1"].PutValue("Fruit"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["A3"].PutValue("Orange"); + worksheet.Cells["A4"].PutValue("Banana"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["B3"].PutValue(5); + worksheet.Cells["B4"].PutValue(8); + + // Add a pivot table + int pivotIdx = worksheet.PivotTables.Add("A1:B4", "E3", "PivotTable1"); + PivotTable pivot = worksheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Quantity"); + + // Add slicers and assign explicit names + SlicerCollection slicers = worksheet.Slicers; + int slicerIdx1 = slicers.Add(pivot, "E5", "Fruit"); + slicers[slicerIdx1].Name = "FruitSlicer1"; + int slicerIdx2 = slicers.Add(pivot, "E7", "Fruit"); + slicers[slicerIdx2].Name = "FruitSlicer2"; + + // List of slicer names to be removed + List slicerNamesToRemove = new List + { + "FruitSlicer1", + "NonExistingSlicer", + "FruitSlicer2" + }; + + // Process each name: attempt removal and log the result + foreach (string name in slicerNamesToRemove) + { + try + { + // Retrieve slicer by name; throws if not found + Slicer slicer = slicers[name]; + slicers.Remove(slicer); + Console.WriteLine($"Removed slicer '{name}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to remove slicer '{name}': {ex.Message}"); + } + } + + // Save the workbook with the remaining slicers (if any) + workbook.Save("SlicersRemoved.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/programmatically-retrieve-slicer-properties-log-them-and-modify-row-height-based-on-logged-values.cs b/slicer/programmatically-retrieve-slicer-properties-log-them-and-modify-row-height-based-on-logged-values.cs new file mode 100644 index 0000000000..11a60b1270 --- /dev/null +++ b/slicer/programmatically-retrieve-slicer-properties-log-them-and-modify-row-height-based-on-logged-values.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerPropertyDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + sheet.Cells["A1"].Value = "Category"; + sheet.Cells["B1"].Value = "Amount"; + sheet.Cells["A2"].Value = "Fruit"; + sheet.Cells["B2"].Value = 120; + sheet.Cells["A3"].Value = "Fruit"; + sheet.Cells["B3"].Value = 80; + sheet.Cells["A4"].Value = "Vegetable"; + sheet.Cells["B4"].Value = 150; + + // Add a pivot table based on the data + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table. + // The second argument must be a valid cell address (e.g., "E1"). + int slicerIdx = sheet.Slicers.Add(pivot, "E1", "Category"); + Slicer slicer = sheet.Slicers[slicerIdx]; + slicer.Name = "CategorySlicer"; + + // Retrieve and log various slicer properties + Console.WriteLine("=== Slicer Properties Before Modification ==="); + Console.WriteLine($"Name: {slicer.Name}"); + Console.WriteLine($"Caption: {slicer.Caption}"); + Console.WriteLine($"RowHeight (points): {slicer.RowHeight}"); + Console.WriteLine($"RowHeightPixel: {slicer.RowHeightPixel}"); + Console.WriteLine($"ColumnWidth (points): {slicer.ColumnWidth}"); + Console.WriteLine($"NumberOfColumns: {slicer.NumberOfColumns}"); + Console.WriteLine($"LockedPosition: {slicer.LockedPosition}"); + + // Example logic: increase row height by 5 points if current height is less than 25 points + double currentRowHeight = slicer.RowHeight; + if (currentRowHeight < 25) + { + double newRowHeight = currentRowHeight + 5; + slicer.RowHeight = newRowHeight; + Console.WriteLine($"RowHeight increased from {currentRowHeight} to {newRowHeight} points."); + } + else + { + Console.WriteLine("RowHeight is already 25 points or more; no change applied."); + } + + // Log properties after modification + Console.WriteLine("=== Slicer Properties After Modification ==="); + Console.WriteLine($"RowHeight (points): {slicer.RowHeight}"); + + // Save the workbook + string outputPath = "SlicerPropertyLogAndModify.xlsx"; + // Ensure the directory exists (use current directory if none specified) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/programmatically-select-specific-slicer-items-based-on-a-predefined-list-of-values.cs b/slicer/programmatically-select-specific-slicer-items-based-on-a-predefined-list-of-values.cs new file mode 100644 index 0000000000..6675f31eb8 --- /dev/null +++ b/slicer/programmatically-select-specific-slicer-items-based-on-a-predefined-list-of-values.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace SlicerSelectionDemo +{ + class Program + { + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Verify that the input workbook exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Values that should be selected in the slicer + string[] valuesToSelect = { "Apple", "Banana" }; + + // Get the first worksheet (adjust if needed) + Worksheet worksheet = workbook.Worksheets[0]; + + // Ensure the worksheet contains at least one slicer + if (worksheet.Slicers.Count == 0) + { + Console.WriteLine("No slicers found on the first worksheet."); + return; + } + + // Access the first slicer (or modify to select by name) + Slicer slicer = worksheet.Slicers[0]; + + // Update selection for each slicer cache item + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + item.Selected = valuesToSelect.Contains(item.Value); + } + + // Apply the changes + slicer.Refresh(); + + // Save the modified workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/remove-an-existing-pivot-connection-from-the-slicer-to-stop-automatic-updates.cs b/slicer/remove-an-existing-pivot-connection-from-the-slicer-to-stop-automatic-updates.cs new file mode 100644 index 0000000000..a2b453f677 --- /dev/null +++ b/slicer/remove-an-existing-pivot-connection-from-the-slicer-to-stop-automatic-updates.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsExamples +{ + public class RemoveSlicerPivotConnectionDemo + { + public static void Main() + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + dataSheet.Name = "Data"; + + // Populate sample data for the pivot table + dataSheet.Cells["A1"].PutValue("Product"); + dataSheet.Cells["A2"].PutValue("Apple"); + dataSheet.Cells["A3"].PutValue("Banana"); + dataSheet.Cells["B1"].PutValue("Sales"); + dataSheet.Cells["B2"].PutValue(100); + dataSheet.Cells["B3"].PutValue(200); + + // Add a worksheet to host the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("PivotTable"); + + // Create a pivot table based on the data range + PivotTableCollection pivotTables = pivotSheet.PivotTables; + int pivotIndex = pivotTables.Add("=Data!A1:B3", "A3", "TestPivotTable"); + PivotTable pivotTable = pivotTables[pivotIndex]; + + // Configure the pivot table fields + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Product column + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Sales column + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Add a slicer linked to the pivot table (field index 0 = Product) + int slicerIndex = pivotSheet.Slicers.Add(pivotTable, "E3", 0); + Slicer slicer = pivotSheet.Slicers[slicerIndex]; + + // Remove the pivot connection from the slicer to stop automatic updates + slicer.RemovePivotConnection(pivotTable); + + // Save the workbook + string outputPath = "RemoveSlicerPivotConnection_out.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + } +} \ No newline at end of file diff --git a/slicer/remove-slicers-from-all-worksheets-in-a-workbook-and-save-a-consolidated-pdf.cs b/slicer/remove-slicers-from-all-worksheets-in-a-workbook-and-save-a-consolidated-pdf.cs new file mode 100644 index 0000000000..89ab8ea7ed --- /dev/null +++ b/slicer/remove-slicers-from-all-worksheets-in-a-workbook-and-save-a-consolidated-pdf.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSlicerRemoval +{ + class Program + { + static void Main() + { + // Load the workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through all worksheets and remove all slicers + foreach (Worksheet sheet in workbook.Worksheets) + { + // Clear the slicer collection for the current worksheet + sheet.Slicers.Clear(); + } + + // Prepare PDF save options to include all sheets + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + SheetSet = SheetSet.All // Export all sheets to the PDF + }; + + // Save the workbook as a consolidated PDF + workbook.Save("output.pdf", pdfOptions); + } + } +} \ No newline at end of file diff --git a/slicer/render-the-workbook-to-pdf-while-preserving-slicer-visual-properties-and-layout.cs b/slicer/render-the-workbook-to-pdf-while-preserving-slicer-visual-properties-and-layout.cs new file mode 100644 index 0000000000..8ae120fcda --- /dev/null +++ b/slicer/render-the-workbook-to-pdf-while-preserving-slicer-visual-properties-and-layout.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSlicerPdfDemo +{ + class Program + { + static void Main() + { + try + { + const string inputPath = "input_with_slicers.xlsx"; + const string outputPath = "output_preserving_slicers.pdf"; + + // Ensure the input workbook exists before loading. + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {Path.GetFullPath(inputPath)}"); + return; + } + + // Load the workbook containing slicers. + Workbook workbook = new Workbook(inputPath); + + // Configure PDF save options to preserve document structure (keeps slicers). + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + ExportDocumentStructure = true + }; + + // Save the workbook as a PDF. + workbook.Save(outputPath, pdfOptions); + + Console.WriteLine($"Workbook successfully rendered to PDF with slicer layout preserved: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/resize-the-slicer-by-assigning-specific-height-and-width-values-for-layout-consistency.cs b/slicer/resize-the-slicer-by-assigning-specific-height-and-width-values-for-layout-consistency.cs new file mode 100644 index 0000000000..baef58874d --- /dev/null +++ b/slicer/resize-the-slicer-by-assigning-specific-height-and-width-values-for-layout-consistency.cs @@ -0,0 +1,41 @@ +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the pivot table + worksheet.Cells["A1"].Value = "Category"; + worksheet.Cells["A2"].Value = "Fruit"; + worksheet.Cells["A3"].Value = "Fruit"; + worksheet.Cells["A4"].Value = "Vegetable"; + + worksheet.Cells["B1"].Value = "Sales"; + worksheet.Cells["B2"].Value = 120; + worksheet.Cells["B3"].Value = 150; + worksheet.Cells["B4"].Value = 200; + + // Add a pivot table based on the data range + int pivotIndex = worksheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivotTable = worksheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Sales"); + + // Add a slicer linked to the "Category" field of the pivot table + int slicerIndex = worksheet.Slicers.Add(pivotTable, "E1", "Category"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Resize the slicer using the Shape's point‑based properties for layout consistency + slicer.Shape.WidthPt = 150; // Width in points + slicer.Shape.HeightPt = 80; // Height in points + + // Save the workbook with the resized slicer + workbook.Save("ResizedSlicer.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/retrieve-a-slicer-programmatically-select-multiple-items-refresh-it-and-save-changes-to-xlsx.cs b/slicer/retrieve-a-slicer-programmatically-select-multiple-items-refresh-it-and-save-changes-to-xlsx.cs new file mode 100644 index 0000000000..5a3e9b30ca --- /dev/null +++ b/slicer/retrieve-a-slicer-programmatically-select-multiple-items-refresh-it-and-save-changes-to-xlsx.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class SlicerSelectionDemo +{ + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Verify that the input file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + throw new FileNotFoundException($"Input file not found: {inputPath}"); + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Assume the slicer is on the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure the worksheet contains at least one slicer + if (sheet.Slicers == null || sheet.Slicers.Count == 0) + throw new InvalidOperationException("No slicers found on the first worksheet."); + + // Retrieve the first slicer + Slicer slicer = sheet.Slicers[0]; + + // Select desired items ("Apple" and "Banana") in the slicer + foreach (SlicerCacheItem item in slicer.SlicerCache.SlicerCacheItems) + { + item.Selected = item.Value == "Apple" || item.Value == "Banana"; + } + + // Refresh the slicer so the connected pivot table reflects the new selections + slicer.Refresh(); + + // Save the updated workbook + workbook.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/slicer/retrieve-the-collection-of-slicers-from-a-worksheet-and-iterate-to-log-each-name.cs b/slicer/retrieve-the-collection-of-slicers-from-a-worksheet-and-iterate-to-log-each-name.cs new file mode 100644 index 0000000000..4cae1016e3 --- /dev/null +++ b/slicer/retrieve-the-collection-of-slicers-from-a-worksheet-and-iterate-to-log-each-name.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; // Needed for ListObject + +class Program +{ + static void Main() + { + try + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); + + // Get the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // OPTIONAL: add a slicer so the collection is not empty (remove if not needed) + // Create sample data + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["B3"].PutValue(20); + + // Add a table (ListObject) covering the sample data + int tableIdx = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[tableIdx]; + + // Add a slicer for the first column of the table + worksheet.Slicers.Add(table, 0, "D1"); + + // Retrieve the slicer collection from the worksheet + SlicerCollection slicers = worksheet.Slicers; + + // Iterate through each slicer and log its name + for (int i = 0; i < slicers.Count; i++) + { + Slicer slicer = slicers[i]; + Console.WriteLine("Slicer Name: " + slicer.Name); + } + + // Define output file path + string outputPath = "SlicersLogDemo.xlsx"; + + // Ensure the directory exists before saving + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/slicer/save-the-workbook-after-each-slicer-modification-to-create-incremental-versioned-files-for-change-tracking.cs b/slicer/save-the-workbook-after-each-slicer-modification-to-create-incremental-versioned-files-for-change-tracking.cs new file mode 100644 index 0000000000..565f202fc4 --- /dev/null +++ b/slicer/save-the-workbook-after-each-slicer-modification-to-create-incremental-versioned-files-for-change-tracking.cs @@ -0,0 +1,89 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerVersioningDemo +{ + public class Program + { + public static void Main() + { + // Initialize a new workbook + Workbook workbook = new Workbook(); + + // ------------------------------------------------- + // 1. Prepare sample data for the pivot table + // ------------------------------------------------- + Worksheet dataSheet = workbook.Worksheets[0]; + dataSheet.Name = "Data"; + + // Header row + dataSheet.Cells["A1"].PutValue("Category"); + dataSheet.Cells["B1"].PutValue("Amount"); + + // Sample rows + dataSheet.Cells["A2"].PutValue("Food"); + dataSheet.Cells["B2"].PutValue(120); + dataSheet.Cells["A3"].PutValue("Beverage"); + dataSheet.Cells["B3"].PutValue(80); + dataSheet.Cells["A4"].PutValue("Food"); + dataSheet.Cells["B4"].PutValue(150); + dataSheet.Cells["A5"].PutValue("Beverage"); + dataSheet.Cells["B5"].PutValue(70); + dataSheet.Cells["A6"].PutValue("Stationery"); + dataSheet.Cells["B6"].PutValue(40); + + // ------------------------------------------------- + // 2. Create a pivot table based on the data + // ------------------------------------------------- + Worksheet pivotSheet = workbook.Worksheets.Add("Pivot"); + int pivotIndex = pivotSheet.PivotTables.Add("A1:B6", "C3", "SalesPivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIndex]; + + // Configure pivot fields + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Category + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Sum of Amount + + // ------------------------------------------------- + // 3. Add a slicer linked to the pivot table + // ------------------------------------------------- + Worksheet slicerSheet = workbook.Worksheets.Add("Slicer"); + int slicerIndex = slicerSheet.Slicers.Add(pivotTable, "A1", "Category"); + Slicer slicer = slicerSheet.Slicers[slicerIndex]; + + // Initial save (version 1) + workbook.Save("Workbook_V1.xlsx"); + + // ------------------------------------------------- + // 4. First modification: change caption + // ------------------------------------------------- + slicer.Caption = "Product Category"; + slicer.Refresh(); // Refresh slicer and underlying pivot table + workbook.Save("Workbook_V2.xlsx"); + + // ------------------------------------------------- + // 5. Second modification: lock the slicer position + // ------------------------------------------------- + slicer.LockedPosition = true; + slicer.Refresh(); + workbook.Save("Workbook_V3.xlsx"); + + // ------------------------------------------------- + // 6. Third modification: change visual layout + // ------------------------------------------------- + slicer.NumberOfColumns = 2; + slicer.WidthPixel = 250; + slicer.HeightPixel = 180; + slicer.Refresh(); + workbook.Save("Workbook_V4.xlsx"); + + // ------------------------------------------------- + // 7. Cleanup + // ------------------------------------------------- + workbook.Dispose(); + + Console.WriteLine("Workbook versions saved successfully."); + } + } +} \ No newline at end of file diff --git a/slicer/save-the-workbook-containing-slicers-to-macroenabled-excel-format-while-retaining-vba-code.cs b/slicer/save-the-workbook-containing-slicers-to-macroenabled-excel-format-while-retaining-vba-code.cs new file mode 100644 index 0000000000..2368cdcc0a --- /dev/null +++ b/slicer/save-the-workbook-containing-slicers-to-macroenabled-excel-format-while-retaining-vba-code.cs @@ -0,0 +1,40 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace MyApp +{ + class SaveWorkbookWithMacros + { + static void Main() + { + try + { + // Path to the input workbook that contains slicers and VBA macros + string inputPath = "input_with_slicers.xlsm"; + + // Verify that the input file exists before attempting to load it + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {Path.GetFullPath(inputPath)}"); + return; + } + + // Load the existing workbook + Workbook workbook = new Workbook(inputPath); + + // Path for the output macro‑enabled workbook + string outputPath = "output_with_macros.xlsm"; + + // Save the workbook preserving VBA macros + workbook.Save(outputPath, SaveFormat.Xlsm); + Console.WriteLine($"Workbook saved successfully to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + // Handle any runtime errors gracefully + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/save-the-workbook-with-pdf-options-to-embed-the-slicers-visual-style-in-the-output-file.cs b/slicer/save-the-workbook-with-pdf-options-to-embed-the-slicers-visual-style-in-the-output-file.cs new file mode 100644 index 0000000000..9964f14fd1 --- /dev/null +++ b/slicer/save-the-workbook-with-pdf-options-to-embed-the-slicers-visual-style-in-the-output-file.cs @@ -0,0 +1,21 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; // Required for PdfSaveOptions + +class Program +{ + static void Main() + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Enable exporting of document structure so that slicer visual styles are preserved in the PDF + pdfOptions.ExportDocumentStructure = true; + + // Save the workbook as PDF using the specified options + workbook.Save("output.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/slicer/save-the-workbook-with-slicers-and-compare-file-sizes-with-a-version-saved-without-slicers.cs b/slicer/save-the-workbook-with-slicers-and-compare-file-sizes-with-a-version-saved-without-slicers.cs new file mode 100644 index 0000000000..7f6c3459b3 --- /dev/null +++ b/slicer/save-the-workbook-with-slicers-and-compare-file-sizes-with-a-version-saved-without-slicers.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace AsposeCellsSlicerSizeComparison +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for a table (A1:C9) + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Year"); + cells["C1"].PutValue("Amount"); + + string[] categories = { "A", "B", "A", "B", "A", "B", "A", "B", "A" }; + int[] years = { 2020, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021 }; + int[] amounts = { 10, 20, 30, 40, 50, 60, 70, 80, 90 }; + + for (int i = 0; i < categories.Length; i++) + { + cells[i + 1, 0].PutValue(categories[i]); // Column A + cells[i + 1, 1].PutValue(years[i]); // Column B + cells[i + 1, 2].PutValue(amounts[i]); // Column C + } + + // Add a table (ListObject) covering the data range + int tableIndex = sheet.ListObjects.Add(0, 0, categories.Length, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + // Use DisplayName instead of Name for compatibility with older Aspose.Cells versions + table.DisplayName = "DataTable"; + + // Add a slicer for the first column (Category) of the table, positioned at cell E2 + int slicerIndex = sheet.Slicers.Add(table, table.ListColumns[0], "E2"); + Slicer slicer = sheet.Slicers[slicerIndex]; + slicer.Caption = "Category Slicer"; + + // Save workbook with slicer + string withSlicerPath = "WorkbookWithSlicer.xlsx"; + workbook.Save(withSlicerPath, SaveFormat.Xlsx); + long sizeWithSlicer = new FileInfo(withSlicerPath).Length; + + // Remove all slicers from the worksheet + sheet.Slicers.Clear(); + + // Save workbook without slicer + string withoutSlicerPath = "WorkbookWithoutSlicer.xlsx"; + workbook.Save(withoutSlicerPath, SaveFormat.Xlsx); + long sizeWithoutSlicer = new FileInfo(withoutSlicerPath).Length; + + // Output the comparison results + Console.WriteLine($"File size with slicer : {sizeWithSlicer} bytes"); + Console.WriteLine($"File size without slicer : {sizeWithoutSlicer} bytes"); + Console.WriteLine($"Size difference : {sizeWithSlicer - sizeWithoutSlicer} bytes"); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/set-slicer-placement-and-ensure-it-remains-unchanged-after-saving-and-reloading-the-workbook.cs b/slicer/set-slicer-placement-and-ensure-it-remains-unchanged-after-saving-and-reloading-the-workbook.cs new file mode 100644 index 0000000000..056418cce7 --- /dev/null +++ b/slicer/set-slicer-placement-and-ensure-it-remains-unchanged-after-saving-and-reloading-the-workbook.cs @@ -0,0 +1,57 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +namespace SlicerPlacementDemo +{ + class Program + { + static void Main() + { + // ---------- Create a new workbook and add data ---------- + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Sample data for a pivot table + sheet.Cells["A1"].Value = "Fruit"; + sheet.Cells["A2"].Value = "Apple"; + sheet.Cells["A3"].Value = "Orange"; + sheet.Cells["A4"].Value = "Banana"; + sheet.Cells["B1"].Value = "Sales"; + sheet.Cells["B2"].Value = 100; + sheet.Cells["B3"].Value = 150; + sheet.Cells["B4"].Value = 200; + + // ---------- Create a pivot table ---------- + int pivotIdx = sheet.PivotTables.Add("A1:B4", "C3", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + + // ---------- Add a slicer linked to the pivot table ---------- + // Destination cell for the slicer is A6, base field index is 0 (Fruit) + int slicerIdx = sheet.Slicers.Add(pivot, "A6", 0); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // ---------- Set the slicer placement ---------- + // Using the obsolete Slicer.Placement property (as per available rule) + slicer.Placement = PlacementType.MoveAndSize; + + // Save the workbook + string filePath = "SlicerPlacementDemo.xlsx"; + workbook.Save(filePath); + + // ---------- Reload the workbook and verify placement ---------- + Workbook loadedWb = new Workbook(filePath); + Worksheet loadedSheet = loadedWb.Worksheets[0]; + Slicer loadedSlicer = loadedSheet.Slicers[0]; + + // Check if the placement persisted + PlacementType placement = loadedSlicer.Placement; + Console.WriteLine("Slicer placement after reload: " + placement); + // Expected output: MoveAndSize + } + } +} \ No newline at end of file diff --git a/slicer/set-slicer-row-height-dynamically-based-on-the-number-of-unique-items-in-the-linked-column.cs b/slicer/set-slicer-row-height-dynamically-based-on-the-number-of-unique-items-in-the-linked-column.cs new file mode 100644 index 0000000000..4db25591c5 --- /dev/null +++ b/slicer/set-slicer-row-height-dynamically-based-on-the-number-of-unique-items-in-the-linked-column.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerDynamicRowHeight +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Sample data in column A (the linked column for the slicer) + cells["A1"].Value = "Category"; + cells["A2"].Value = "Fruit"; + cells["A3"].Value = "Fruit"; + cells["A4"].Value = "Vegetable"; + cells["A5"].Value = "Grain"; + cells["A6"].Value = "Fruit"; + cells["A7"].Value = "Grain"; + + // Create a pivot table based on the data + int pivotIdx = sheet.PivotTables.Add("A1:A7", "C3", "PivotTable1"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // use column A as row field + + // Add a slicer linked to the pivot table for the "Category" field + int slicerIdx = sheet.Slicers.Add(pivot, "E3", "Category"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // ----- Dynamic RowHeight calculation ----- + // Determine the number of unique items in the linked column (A) + HashSet uniqueItems = new HashSet(); + for (int row = 1; row <= cells.MaxDataRow; row++) // start from row 2 (index 1) to skip header + { + object val = cells[row, 0].Value; + if (val != null) + uniqueItems.Add(val.ToString()); + } + int uniqueCount = uniqueItems.Count; + + // Example logic: smaller row height for many items, larger for few items + // Adjust the per‑row height (in points) + if (uniqueCount > 10) + slicer.RowHeight = 12; // compact rows + else if (uniqueCount > 5) + slicer.RowHeight = 16; + else + slicer.RowHeight = 20; // spacious rows + + // Optionally adjust the overall slicer height so all items are visible + slicer.Height = slicer.RowHeight * uniqueCount; + + // Save the workbook + workbook.Save("SlicerDynamicRowHeight.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/set-slicer-width-to-150-pixels-and-verify-its-appearance-on-the-worksheet.cs b/slicer/set-slicer-width-to-150-pixels-and-verify-its-appearance-on-the-worksheet.cs new file mode 100644 index 0000000000..0bae535c9d --- /dev/null +++ b/slicer/set-slicer-width-to-150-pixels-and-verify-its-appearance-on-the-worksheet.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerWidthDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate worksheet with sample data for a pivot table + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Amount"); + sheet.Cells["A2"].PutValue("Fruit"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["A3"].PutValue("Vegetable"); + sheet.Cells["B3"].PutValue(80); + sheet.Cells["A4"].PutValue("Fruit"); + sheet.Cells["B4"].PutValue(150); + sheet.Cells["A5"].PutValue("Vegetable"); + sheet.Cells["B5"].PutValue(70); + + // Add a pivot table based on the data range + PivotTableCollection pivots = sheet.PivotTables; + int pivotIdx = pivots.Add("A1:B5", "D2", "PivotTable1"); + PivotTable pivot = pivots[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table for the "Category" field + // Correct parameter order: destination cell first, then the field name + int slicerIdx = sheet.Slicers.Add(pivot, "F2", "Category"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Set the slicer width to 150 pixels + slicer.WidthPixel = 150; + + // Verify that the width was set correctly + if (slicer.WidthPixel == 150) + { + Console.WriteLine("Slicer width successfully set to 150 pixels."); + } + else + { + Console.WriteLine($"Unexpected slicer width: {slicer.WidthPixel} pixels."); + } + + // Save the workbook to a file + string outputPath = "SlicerWidthDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/set-the-slicer-caption-to-a-custom-string-to-improve-user-understanding.cs b/slicer/set-the-slicer-caption-to-a-custom-string-to-improve-user-understanding.cs new file mode 100644 index 0000000000..89147e2a8e --- /dev/null +++ b/slicer/set-the-slicer-caption-to-a-custom-string-to-improve-user-understanding.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerCaptionDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate worksheet with sample data for a pivot table + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("Fruit"); + worksheet.Cells["A3"].PutValue("Vegetable"); + worksheet.Cells["A4"].PutValue("Fruit"); + worksheet.Cells["A5"].PutValue("Vegetable"); + + worksheet.Cells["B1"].PutValue("Sales"); + worksheet.Cells["B2"].PutValue(120); + worksheet.Cells["B3"].PutValue(80); + worksheet.Cells["B4"].PutValue(150); + worksheet.Cells["B5"].PutValue(90); + + // Add a table to the data range (required for slicer creation) + int tableIndex = worksheet.ListObjects.Add("Table1", "A1:B5", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Create a pivot table based on the table data. + // Use the data range address directly because ListObject.Name may not be available in all versions. + int pivotIndex = worksheet.PivotTables.Add("A1:B5", "D2", "PivotTable1"); + PivotTable pivotTable = worksheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Sales"); + pivotTable.CalculateData(); + + // Add a slicer linked to the pivot table for the "Category" field. + // Parameters: pivot table, column index, row index, height (in rows). + int slicerIndex = worksheet.Slicers.Add(pivotTable, 0, 1, 4); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Set a custom caption for the slicer + slicer.Caption = "Select Category"; + slicer.ShowCaption = true; // Ensure the caption header is visible + + // Save the workbook to a file + string outputPath = "SlicerWithCustomCaption.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/set-the-slicer-item-sorting-order-to-descending-based-on-underlying-data-values.cs b/slicer/set-the-slicer-item-sorting-order-to-descending-based-on-underlying-data-values.cs new file mode 100644 index 0000000000..1cd3b616bc --- /dev/null +++ b/slicer/set-the-slicer-item-sorting-order-to-descending-based-on-underlying-data-values.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +class SetSlicerSortOrder +{ + static void Main() + { + // Load an existing workbook that contains a slicer + Workbook workbook = new Workbook("input.xlsx"); + + // Access the first worksheet (adjust index if needed) + Worksheet sheet = workbook.Worksheets[0]; + + // Retrieve the slicer collection from the worksheet + SlicerCollection slicers = sheet.Slicers; + + // Ensure there is at least one slicer present + if (slicers.Count > 0) + { + // Get the first slicer in the collection + Slicer slicer = slicers[0]; + + // Set the slicer items to be sorted in descending order + slicer.SortOrderType = SortOrder.Descending; + } + + // Save the workbook with the updated slicer sorting + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/set-the-slicer-to-be-printable-so-it-appears-when-the-worksheet-is-printed-to-paper.cs b/slicer/set-the-slicer-to-be-printable-so-it-appears-when-the-worksheet-is-printed-to-paper.cs new file mode 100644 index 0000000000..0977b2df05 --- /dev/null +++ b/slicer/set-the-slicer-to-be-printable-so-it-appears-when-the-worksheet-is-printed-to-paper.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; // For PivotFieldType +using Aspose.Cells.Slicers; // For slicer support (optional) + +namespace SlicerPrintableDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Create a new workbook and get the first worksheet + var workbook = new Workbook(); + var sheet = workbook.Worksheets[0]; + var cells = sheet.Cells; + + // Populate sample data for the pivot table + cells["A1"].Value = "Category"; + cells["A2"].Value = "A"; + cells["A3"].Value = "B"; + cells["A4"].Value = "C"; + + cells["B1"].Value = "Value"; + cells["B2"].Value = 10; + cells["B3"].Value = 20; + cells["B4"].Value = 30; + + // Add a pivot table based on the data range + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "MyPivot"); + var pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Category"); + pivot.AddFieldToArea(PivotFieldType.Data, "Value"); + + // Add a slicer linked to the pivot table + int slicerIdx = sheet.Slicers.Add(pivot, "E1", "Category"); + var slicer = sheet.Slicers[slicerIdx]; + + // Make the slicer printable so it appears on printed pages + slicer.Shape.IsPrintable = true; + + // Define output file path + string outputPath = "SlicerPrintableDemo.xlsx"; + + // Ensure the output directory exists (prevents FileNotFoundException on save) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/set-the-worksheet-print-area-to-slicer-bounds-then-render-the-slicer-as-an-image-file.cs b/slicer/set-the-worksheet-print-area-to-slicer-bounds-then-render-the-slicer-as-an-image-file.cs new file mode 100644 index 0000000000..0a01601df1 --- /dev/null +++ b/slicer/set-the-worksheet-print-area-to-slicer-bounds-then-render-the-slicer-as-an-image-file.cs @@ -0,0 +1,96 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; // Pivot table related types + +namespace SlicerRenderDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + sheet.Cells["A1"].Value = "Fruit"; + sheet.Cells["B1"].Value = "Year"; + sheet.Cells["C1"].Value = "Amount"; + + string[] fruits = { "Apple", "Banana", "Apple", "Banana", "Apple", "Banana" }; + int[] years = { 2020, 2020, 2021, 2021, 2022, 2022 }; + int[] amounts = { 50, 70, 60, 80, 55, 75 }; + + for (int i = 0; i < fruits.Length; i++) + { + sheet.Cells[i + 1, 0].Value = fruits[i]; + sheet.Cells[i + 1, 1].Value = years[i]; + sheet.Cells[i + 1, 2].Value = amounts[i]; + } + + // Add a pivot table based on the data range + PivotTableCollection pivots = sheet.PivotTables; + int pivotIdx = pivots.Add("A1:C7", "E3", "FruitPivot"); + PivotTable pivot = pivots[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Column, "Year"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.PivotTableStyleType = PivotTableStyleType.PivotTableStyleMedium9; + pivot.RefreshData(); + pivot.CalculateData(); + + // Add a slicer linked to the pivot table for the "Fruit" field + SlicerCollection slicers = sheet.Slicers; + int slicerIdx = slicers.Add(pivot, "Fruit", "F2"); + Slicer slicer = slicers[slicerIdx]; + + // Ensure the slicer is printable (use Shape.IsPrintable as IsPrintable is obsolete) + slicer.Shape.IsPrintable = true; + + // Retrieve the slicer's shape to determine its bounds + var slicerShape = slicer.Shape; + + int ulRow = slicerShape.UpperLeftRow; // Upper‑left row index (0‑based) + int ulCol = slicerShape.UpperLeftColumn; // Upper‑left column index (0‑based) + int lrRow = slicerShape.LowerRightRow; // Lower‑right row index (0‑based) + int lrCol = slicerShape.LowerRightColumn; // Lower‑right column index (0‑based) + + // Convert the corner cells to their A1 style names + string startCell = sheet.Cells[ulRow, ulCol].Name; + string endCell = sheet.Cells[lrRow, lrCol].Name; + + // Set the worksheet's print area to exactly the slicer's bounds + sheet.PageSetup.PrintArea = $"{startCell}:{endCell}"; + + // Configure image rendering options: render only the defined area + ImageOrPrintOptions options = new ImageOrPrintOptions + { + ImageType = Aspose.Cells.Drawing.ImageType.Png, + OnePagePerSheet = true, + OnlyArea = true // Render only the print area without scaling + }; + + // Render the worksheet (which now contains only the slicer) to an image file + SheetRender renderer = new SheetRender(sheet, options); + string imagePath = "SlicerImage.png"; + renderer.ToImage(0, imagePath); + + // Save the workbook (optional, to verify the slicer and print area) + string workbookPath = "SlicerWorkbook.xlsx"; + workbook.Save(workbookPath); + + Console.WriteLine($"Slicer rendered to image file '{imagePath}'."); + Console.WriteLine($"Workbook saved as '{workbookPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/synchronize-two-slicers-so-that-selecting-an-item-in-one-updates-the-other-automatically.cs b/slicer/synchronize-two-slicers-so-that-selecting-an-item-in-one-updates-the-other-automatically.cs new file mode 100644 index 0000000000..8e32dad960 --- /dev/null +++ b/slicer/synchronize-two-slicers-so-that-selecting-an-item-in-one-updates-the-other-automatically.cs @@ -0,0 +1,71 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace SlicerSyncDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (lifecycle rule: create) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data + cells["A1"].Value = "Fruit"; + cells["B1"].Value = "Year"; + cells["C1"].Value = "Amount"; + + string[] fruits = { "Apple", "Banana", "Cherry", "Apple", "Banana", "Cherry" }; + int[] years = { 2020, 2020, 2020, 2021, 2021, 2021 }; + int[] amounts = { 50, 70, 90, 60, 80, 100 }; + + for (int i = 0; i < fruits.Length; i++) + { + cells[i + 1, 0].Value = fruits[i]; + cells[i + 1, 1].Value = years[i]; + cells[i + 1, 2].Value = amounts[i]; + } + + // Add a pivot table based on the data range + PivotTableCollection pivots = sheet.PivotTables; + int pivotIdx = pivots.Add("A1:C7", "E3", "FruitPivot"); + PivotTable pivot = pivots[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Column, "Year"); + pivot.AddFieldToArea(PivotFieldType.Data, "Amount"); + pivot.PivotTableStyleType = PivotTableStyleType.PivotTableStyleMedium9; + pivot.RefreshData(); + pivot.CalculateData(); + + // Add first slicer for the "Fruit" field + SlicerCollection slicers = sheet.Slicers; + int slicerIdx1 = slicers.Add(pivot, "G1", "Fruit"); + Slicer slicer1 = slicers[slicerIdx1]; + slicer1.Caption = "Fruit Slicer 1"; + + // Add second slicer for the same "Fruit" field + int slicerIdx2 = slicers.Add(pivot, "G15", "Fruit"); + Slicer slicer2 = slicers[slicerIdx2]; + slicer2.Caption = "Fruit Slicer 2"; + + // ---- Synchronization demonstration ---- + // Select "Banana" in the first slicer by manipulating its SlicerCache + foreach (SlicerCacheItem item in slicer1.SlicerCache.SlicerCacheItems) + { + // Set Selected = true only for "Banana", false for others + item.Selected = string.Equals(item.Value?.ToString(), "Banana", StringComparison.OrdinalIgnoreCase); + } + + // Refresh both slicers so they reflect the same selection + slicer1.Refresh(); + slicer2.Refresh(); + + // Save the workbook (lifecycle rule: save) + workbook.Save("SlicerSyncDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/unselect-all-items-in-a-slicer-call-refresh-and-export-the-workbook-to-pdf-preserving-slicer-appearance.cs b/slicer/unselect-all-items-in-a-slicer-call-refresh-and-export-the-workbook-to-pdf-preserving-slicer-appearance.cs new file mode 100644 index 0000000000..a151b56e6c --- /dev/null +++ b/slicer/unselect-all-items-in-a-slicer-call-refresh-and-export-the-workbook-to-pdf-preserving-slicer-appearance.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; + +class SlicerUnselectAndExport +{ + static void Main() + { + // Load an existing workbook that contains a slicer + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get the slicer collection for the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Process each slicer + for (int i = 0; i < slicers.Count; i++) + { + Slicer slicer = slicers[i]; + + // Unselect all items by showing all items (no filter applied) + slicer.ShowAllItems = true; + + // Refresh the slicer (also refreshes the underlying PivotTable) + slicer.Refresh(); + } + } + + // Prepare PDF save options (default options preserve slicer appearance) + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Export the workbook to PDF, preserving slicer visual appearance + workbook.Save("output.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/slicer/update-slicer-properties-across-all-worksheets-in-a-workbook-to-enforce-a-corporate-style.cs b/slicer/update-slicer-properties-across-all-worksheets-in-a-workbook-to-enforce-a-corporate-style.cs new file mode 100644 index 0000000000..189d148333 --- /dev/null +++ b/slicer/update-slicer-properties-across-all-worksheets-in-a-workbook-to-enforce-a-corporate-style.cs @@ -0,0 +1,56 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +class UpdateSlicerStyle +{ + static void Main() + { + // Load the existing workbook + Workbook workbook = new Workbook("InputWorkbook.xlsx"); + + // Define corporate style settings + SlicerStyleType corporateStyle = SlicerStyleType.SlicerStyleDark2; + int corporateColumns = 2; + int corporateWidthPixel = 250; + int corporateHeightPixel = 150; + bool corporateLockedPosition = true; + bool corporateShowCaption = true; + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Access the slicer collection of the current worksheet + SlicerCollection slicers = sheet.Slicers; + + // Apply corporate style to each slicer + for (int i = 0; i < slicers.Count; i++) + { + Slicer slicer = slicers[i]; + + // Set built‑in style + slicer.StyleType = corporateStyle; + + // Set number of columns + slicer.NumberOfColumns = corporateColumns; + + // Set size in pixels + slicer.WidthPixel = corporateWidthPixel; + slicer.HeightPixel = corporateHeightPixel; + + // Lock position to prevent user moving/resizing + slicer.LockedPosition = corporateLockedPosition; + + // Ensure caption visibility matches corporate policy + slicer.ShowCaption = corporateShowCaption; + + // Refresh slicer to apply changes to linked pivot tables + slicer.Refresh(); + } + } + + // Save the modified workbook + workbook.Save("OutputWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/update-slicer-style-based-on-datadriven-criteria-using-the-api.cs b/slicer/update-slicer-style-based-on-datadriven-criteria-using-the-api.cs new file mode 100644 index 0000000000..badbbda04b --- /dev/null +++ b/slicer/update-slicer-style-based-on-datadriven-criteria-using-the-api.cs @@ -0,0 +1,61 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +class UpdateSlicerStyle +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["B1"].PutValue("Amount"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["B2"].PutValue(120); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["B3"].PutValue(80); + worksheet.Cells["A4"].PutValue("C"); + worksheet.Cells["B4"].PutValue(200); + + // Add a pivot table based on the data range + int pivotIndex = worksheet.PivotTables.Add("A1:B4", "D1", "PivotTable1"); + PivotTable pivotTable = worksheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Category field + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Amount field + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Add a slicer linked to the Category field of the pivot table + int slicerIndex = worksheet.Slicers.Add(pivotTable, "F1", "Category"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Compute total amount from the source data + double totalAmount = 0; + for (int row = 1; row <= 3; row++) + { + totalAmount += worksheet.Cells[row, 1].DoubleValue; + } + + // Update slicer style based on the total amount + if (totalAmount > 300) + { + // Use a dark style when the total exceeds the threshold + slicer.StyleType = SlicerStyleType.SlicerStyleDark2; + } + else + { + // Use a light style otherwise + slicer.StyleType = SlicerStyleType.SlicerStyleLight2; + } + + // Refresh the slicer to apply any pending changes + slicer.Refresh(); + + // Save the workbook + workbook.Save("UpdatedSlicerStyle.xlsx"); + } +} \ No newline at end of file diff --git a/slicer/use-a-configuration-flag-to-decide-whether-to-keep-slicers-when-exporting-the-workbook-to-pdf.cs b/slicer/use-a-configuration-flag-to-decide-whether-to-keep-slicers-when-exporting-the-workbook-to-pdf.cs new file mode 100644 index 0000000000..564adefaea --- /dev/null +++ b/slicer/use-a-configuration-flag-to-decide-whether-to-keep-slicers-when-exporting-the-workbook-to-pdf.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Slicers; +using Aspose.Cells.Rendering; + +namespace AsposeCellsSlicerPdfExport +{ + class Program + { + static void Main() + { + try + { + // Configuration flag: true to keep slicers in the PDF, false to hide them + bool keepSlicersInPdf = GetKeepSlicersFlag(); + + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate data for the slicer + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["A4"].PutValue("A"); + sheet.Cells["A5"].PutValue("B"); + + // Convert the range to a table (ListObject) so that a slicer can be attached + int tableIndex = sheet.ListObjects.Add("A1", "A5", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Set a display name for the table (Name property may not be available in some versions) + table.DisplayName = "CategoryTable"; + + // Add a slicer linked to the table (column index 0 corresponds to the first column) + int slicerIndex = sheet.Slicers.Add(table, 0, "D1"); + Slicer slicer = sheet.Slicers[slicerIndex]; + + // Control slicer visibility in the PDF using Shape.IsPrintable + slicer.Shape.IsPrintable = keepSlicersInPdf; + + // Configure PDF save options (default settings are sufficient) + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Save the workbook to PDF + string outputPath = "ExportedWorkbook.pdf"; + workbook.Save(outputPath, pdfOptions); + Console.WriteLine($"Workbook exported successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + // Placeholder for obtaining the configuration flag (could be from app settings, env variable, etc.) + static bool GetKeepSlicersFlag() + { + // For demonstration, we simply return true. + // Replace this logic with actual configuration retrieval as needed. + return true; + } + } +} \ No newline at end of file diff --git a/slicer/use-slicercacheitems-to-select-items-based-on-external-csv-data-then-refresh-the-slicer.cs b/slicer/use-slicercacheitems-to-select-items-based-on-external-csv-data-then-refresh-the-slicer.cs new file mode 100644 index 0000000000..828ae3444a --- /dev/null +++ b/slicer/use-slicercacheitems-to-select-items-based-on-external-csv-data-then-refresh-the-slicer.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Cells; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerCsvDemo +{ + class Program + { + static void Main() + { + try + { + const string workbookPath = "input.xlsx"; + const string csvPath = "filter.csv"; + const string outputPath = "output.xlsx"; + + // Verify input files exist + if (!File.Exists(workbookPath)) + { + Console.WriteLine($"Workbook file not found: {workbookPath}"); + return; + } + + if (!File.Exists(csvPath)) + { + Console.WriteLine($"CSV file not found: {csvPath}"); + return; + } + + // Load workbook containing a pivot table and slicer + Workbook workbook = new Workbook(workbookPath); + // Refresh all data connections (pivot tables, slicers, etc.) + workbook.Worksheets.RefreshAll(); + + // Read filter values from CSV (one value per line) + string[] csvValues = File.ReadAllLines(csvPath) + .Select(line => line.Trim()) + .Where(line => !string.IsNullOrEmpty(line)) + .ToArray(); + + // Locate the first slicer in the workbook + Slicer slicer = null; + foreach (Worksheet ws in workbook.Worksheets) + { + if (ws.Slicers.Count > 0) + { + slicer = ws.Slicers[0]; + break; + } + } + + if (slicer == null) + { + Console.WriteLine("No slicer found in the workbook."); + return; + } + + // Access slicer cache items + SlicerCacheItemCollection cacheItems = slicer.SlicerCache.SlicerCacheItems; + + // Deselect all items + foreach (SlicerCacheItem item in cacheItems) + { + item.Selected = false; + } + + // Select items matching CSV values + foreach (string value in csvValues) + { + SlicerCacheItem match = cacheItems.FirstOrDefault(i => + i.Value.Equals(value, StringComparison.OrdinalIgnoreCase)); + if (match != null) + { + match.Selected = true; + } + } + + // Refresh slicer (updates underlying pivot table) + slicer.Refresh(); + + // Save modified workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/slicer/use-the-workbooks-calculate-method-after-slicer-refresh-to-ensure-formulas-reflect-the-new-filter.cs b/slicer/use-the-workbooks-calculate-method-after-slicer-refresh-to-ensure-formulas-reflect-the-new-filter.cs new file mode 100644 index 0000000000..22664afee9 --- /dev/null +++ b/slicer/use-the-workbooks-calculate-method-after-slicer-refresh-to-ensure-formulas-reflect-the-new-filter.cs @@ -0,0 +1,60 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsSlicerCalculateDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet (data source) + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + + // Populate sample data + dataSheet.Cells["A1"].PutValue("Product"); + dataSheet.Cells["B1"].PutValue("Sales"); + dataSheet.Cells["A2"].PutValue("Apple"); + dataSheet.Cells["B2"].PutValue(120); + dataSheet.Cells["A3"].PutValue("Banana"); + dataSheet.Cells["B3"].PutValue(80); + dataSheet.Cells["A4"].PutValue("Orange"); + dataSheet.Cells["B4"].PutValue(150); + + // Add a worksheet that will contain the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("PivotSheet"); + int pivotIdx = pivotSheet.PivotTables.Add("A1:B4", "C3", "SalesPivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIdx]; + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Product + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Sales + + // Add a worksheet that will host the slicer + Worksheet slicerSheet = workbook.Worksheets.Add("SlicerSheet"); + int slicerIdx = slicerSheet.Slicers.Add(pivotTable, "A1", "Product"); + Slicer slicer = slicerSheet.Slicers[slicerIdx]; + + // Insert a formula that depends on the pivot table (GETPIVOTDATA example) + // This formula will sum sales for "Apple". It will be recalculated after the slicer refresh. + pivotSheet.Cells["E2"].Formula = "=GETPIVOTDATA(\"Sales\",C3,\"Product\",\"Apple\")"; + + // Change source data to demonstrate that slicer filtering affects the pivot and formula + dataSheet.Cells["A2"].PutValue("Apple"); // keep Apple + dataSheet.Cells["A3"].PutValue("Apple"); // change Banana to Apple + dataSheet.Cells["B3"].PutValue(200); // new sales value for the added Apple row + + // Refresh the slicer – this also refreshes the underlying pivot table + slicer.Refresh(); + + // After slicer refresh, recalculate all formulas so that the GETPIVOTDATA result is up‑to‑date + workbook.CalculateFormula(); + + // Output the calculated result to the console + Console.WriteLine("Calculated sales for Apple (E2): " + pivotSheet.Cells["E2"].StringValue); + + // Save the workbook (using the standard save rule) + workbook.Save("SlicerRefreshWithCalculate.xlsx"); + } + } +} \ No newline at end of file diff --git a/slicer/use-worksheetslicersremoveall-to-clear-every-slicer-from-a-sheet-then-save-the-workbook-as-xlsx.cs b/slicer/use-worksheetslicersremoveall-to-clear-every-slicer-from-a-sheet-then-save-the-workbook-as-xlsx.cs new file mode 100644 index 0000000000..a8d9a96c69 --- /dev/null +++ b/slicer/use-worksheetslicersremoveall-to-clear-every-slicer-from-a-sheet-then-save-the-workbook-as-xlsx.cs @@ -0,0 +1,19 @@ +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet (or any specific worksheet) + Worksheet worksheet = workbook.Worksheets[0]; + + // Clear all slicers from this worksheet + worksheet.Slicers.Clear(); + + // Save the workbook as an XLSX file + workbook.Save("ClearedSlicers.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/slicer/validate-that-slicer-placement-coordinates-remain-consistent-after-saving-and-reloading-the-workbook.cs b/slicer/validate-that-slicer-placement-coordinates-remain-consistent-after-saving-and-reloading-the-workbook.cs new file mode 100644 index 0000000000..164efc0b82 --- /dev/null +++ b/slicer/validate-that-slicer-placement-coordinates-remain-consistent-after-saving-and-reloading-the-workbook.cs @@ -0,0 +1,81 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; +using Aspose.Cells.Drawing; + +namespace SlicerPlacementValidation +{ + class Program + { + static void Main() + { + // -------------------- Create workbook and data -------------------- + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Sample data for a pivot table + cells["A1"].Value = "Fruit"; + cells["B1"].Value = "Sales"; + cells["A2"].Value = "Apple"; + cells["B2"].Value = 120; + cells["A3"].Value = "Orange"; + cells["B3"].Value = 150; + cells["A4"].Value = "Banana"; + cells["B4"].Value = 90; + + // -------------------- Create pivot table -------------------- + int pivotIdx = sheet.PivotTables.Add("A1:B4", "D1", "FruitPivot"); + PivotTable pivot = sheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, "Fruit"); + pivot.AddFieldToArea(PivotFieldType.Data, "Sales"); + pivot.RefreshData(); + pivot.CalculateData(); + + // -------------------- Add slicer linked to the pivot table -------------------- + // Destination cell for slicer upper‑left corner is E1 + int slicerIdx = sheet.Slicers.Add(pivot, "E1", "Fruit"); + Slicer slicer = sheet.Slicers[slicerIdx]; + + // Set explicit placement coordinates via the underlying Shape object + SlicerShape shape = slicer.Shape; + shape.Left = 100; // pixels from left column + shape.Top = 50; // pixels from top row + shape.Width = 200; // pixels + shape.Height = 150; // pixels + + // Store original coordinates for later comparison + int originalLeft = shape.Left; + int originalTop = shape.Top; + int originalWidth = shape.Width; + int originalHeight = shape.Height; + + // -------------------- Save workbook -------------------- + string filePath = "SlicerPlacementDemo.xlsx"; + workbook.Save(filePath, SaveFormat.Xlsx); + + // -------------------- Load workbook -------------------- + Workbook loadedWorkbook = new Workbook(filePath); + Worksheet loadedSheet = loadedWorkbook.Worksheets[0]; + Slicer loadedSlicer = loadedSheet.Slicers[slicerIdx]; + SlicerShape loadedShape = loadedSlicer.Shape; + + // Retrieve coordinates after reload + int loadedLeft = loadedShape.Left; + int loadedTop = loadedShape.Top; + int loadedWidth = loadedShape.Width; + int loadedHeight = loadedShape.Height; + + // -------------------- Validate consistency -------------------- + bool isConsistent = originalLeft == loadedLeft && + originalTop == loadedTop && + originalWidth == loadedWidth && + originalHeight == loadedHeight; + + Console.WriteLine("Slicer placement validation result: " + (isConsistent ? "Consistent" : "Inconsistent")); + Console.WriteLine($"Original - Left:{originalLeft}, Top:{originalTop}, Width:{originalWidth}, Height:{originalHeight}"); + Console.WriteLine($"Loaded - Left:{loadedLeft}, Top:{loadedTop}, Width:{loadedWidth}, Height:{loadedHeight}"); + } + } +} \ No newline at end of file diff --git a/slicer/validate-that-the-slicer-printable-flag-is-true-before-exporting-the-workbook-to-pdf.cs b/slicer/validate-that-the-slicer-printable-flag-is-true-before-exporting-the-workbook-to-pdf.cs new file mode 100644 index 0000000000..dcf49315e4 --- /dev/null +++ b/slicer/validate-that-the-slicer-printable-flag-is-true-before-exporting-the-workbook-to-pdf.cs @@ -0,0 +1,39 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; +using Aspose.Cells.Rendering; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate some data to create a table (required for slicer) + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["A3"].PutValue("B"); + + // Add a ListObject (table) covering the data range + ListObject table = worksheet.ListObjects[worksheet.ListObjects.Add("A1", "A3", true)]; + + // Add a slicer linked to the table at cell D1 + int slicerIndex = worksheet.Slicers.Add(table, 0, "D1"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // Validate that the slicer is printable; set to true if not + if (!slicer.IsPrintable) + { + slicer.IsPrintable = true; + } + + // Configure PDF save options (default options are sufficient for this example) + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Export the workbook to PDF + workbook.Save("output.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/slicer/write-a-unit-test-verifying-that-slicerrefresh-updates-the-linked-pivot-tables-row-count-as-expected.cs b/slicer/write-a-unit-test-verifying-that-slicerrefresh-updates-the-linked-pivot-tables-row-count-as-expected.cs new file mode 100644 index 0000000000..fa13e8532f --- /dev/null +++ b/slicer/write-a-unit-test-verifying-that-slicerrefresh-updates-the-linked-pivot-tables-row-count-as-expected.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Slicers; + +namespace AsposeCellsTests +{ + public class SlicerRefreshTests + { + public static void Main(string[] args) + { + try + { + RunTest(); + Console.WriteLine("Test completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + + private static void RunTest() + { + try + { + // Create a new workbook and a data worksheet + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + dataSheet.Name = "Data"; + + // Populate source data + dataSheet.Cells["A1"].PutValue("Product"); + dataSheet.Cells["B1"].PutValue("Sales"); + dataSheet.Cells["A2"].PutValue("Apple"); + dataSheet.Cells["B2"].PutValue(100); + dataSheet.Cells["A3"].PutValue("Banana"); + dataSheet.Cells["B3"].PutValue(200); + + // Add a worksheet for the pivot table and create the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("Pivot"); + int pivotIdx = pivotSheet.PivotTables.Add("Data!A1:B3", "C3", "PivotTable1"); + PivotTable pivot = pivotSheet.PivotTables[pivotIdx]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Product column as row field + pivot.AddFieldToArea(PivotFieldType.Data, 1); // Sales column as data field + + // Calculate initial pivot data + pivot.CalculateData(); + + // Capture the initial number of row items in the pivot table + int initialRowCount = pivot.RowFields[0].PivotItems.Count; + + // Add a slicer linked to the pivot table (based on the Product field) + int slicerIdx = pivotSheet.Slicers.Add(pivot, "A1", "Product"); + Slicer slicer = pivotSheet.Slicers[slicerIdx]; + + // Modify the source data by adding a new distinct product + dataSheet.Cells["A4"].PutValue("Orange"); + dataSheet.Cells["B4"].PutValue(150); + + // Refresh the slicer, which also refreshes the linked pivot table + slicer.Refresh(); + + // After refresh, the pivot table should contain one additional row item + int refreshedRowCount = pivot.RowFields[0].PivotItems.Count; + + // Verify that the row count increased by exactly one + if (refreshedRowCount != initialRowCount + 1) + { + throw new InvalidOperationException( + $"Row count mismatch. Expected {initialRowCount + 1}, but got {refreshedRowCount}."); + } + + // Save the workbook (optional for visual verification) + string outputPath = "SlicerRefreshTest.xlsx"; + try + { + workbook.Save(outputPath, SaveFormat.Xlsx); + } + catch (Exception saveEx) + { + Console.WriteLine($"Failed to save workbook: {saveEx.Message}"); + } + } + catch (Exception ex) + { + // Propagate exception to the outer handler + throw new ApplicationException("Test execution failed.", ex); + } + } + } +} \ No newline at end of file