diff --git a/working-with-tables/add-a-calculated-column-that-uses-the-if-function-to-categorize-rows-based-on-a-numeric-threshold.cs b/working-with-tables/add-a-calculated-column-that-uses-the-if-function-to-categorize-rows-based-on-a-numeric-threshold.cs new file mode 100644 index 0000000000..27662464ee --- /dev/null +++ b/working-with-tables/add-a-calculated-column-that-uses-the-if-function-to-categorize-rows-based-on-a-numeric-threshold.cs @@ -0,0 +1,40 @@ +using Aspose.Cells; +using System; + +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 numeric data in column A + cells["A1"].PutValue("Value"); + cells["A2"].PutValue(50); + cells["A3"].PutValue(150); + cells["A4"].PutValue(80); + cells["A5"].PutValue(200); + + // Add header for the calculated column in column B + cells["B1"].PutValue("Category"); + + // Define the numeric threshold for categorization + double threshold = 100; + + // Apply IF formula to each row to categorize based on the threshold + for (int row = 2; row <= 5; row++) + { + // Formula: =IF(A{row}>threshold,"High","Low") + string formula = $"=IF(A{row}>{threshold},\"High\",\"Low\")"; + cells[$"B{row}"].Formula = formula; + } + + // Calculate all formulas in the workbook + workbook.CalculateFormula(); + + // Save the workbook to a file + workbook.Save("CalculatedColumn.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/add-a-column-to-a-table-and-set-its-validation-to-a-list-sourced-from-a-table-column.cs b/working-with-tables/add-a-column-to-a-table-and-set-its-validation-to-a-list-sourced-from-a-table-column.cs new file mode 100644 index 0000000000..b88673e8f2 --- /dev/null +++ b/working-with-tables/add-a-column-to-a-table-and-set-its-validation-to-a-list-sourced-from-a-table-column.cs @@ -0,0 +1,65 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsTableValidationDemo +{ + 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 (including the source list column) + // Header row + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Options"); // This column will be the source list + cells["C1"].PutValue("Value"); + cells["D1"].PutValue("Choice"); // Column that will have validation + + // Data rows + for (int i = 2; i <= 5; i++) + { + cells[$"A{i}"].PutValue(i - 1); // ID + cells[$"B{i}"].PutValue($"Option{i - 1}"); // Options (source list) + cells[$"C{i}"].PutValue((i - 1) * 10); // Some other value + // D column left empty – will receive validation + } + + // Add a ListObject (table) that includes the new column D + // Table range: A1:D5, hasHeaders = true + int tableIndex = sheet.ListObjects.Add("A1", "D5", true); + ListObject table = sheet.ListObjects[tableIndex]; + // Use DisplayName to set the table name (Name property not available in some versions) + table.DisplayName = "SampleTable"; + + // Define the area for validation: column D (index 3), rows 2‑5 (excluding header) + CellArea validationArea = CellArea.CreateCellArea(1, 3, 4, 3); // rows 1‑4 zero‑based, column 3 + + // Add validation to the worksheet + ValidationCollection validations = sheet.Validations; + int validationIndex = validations.Add(validationArea); + Validation validation = validations[validationIndex]; + + // Configure validation as a list sourced from the "Options" column (B2:B5) + validation.Type = ValidationType.List; + validation.InCellDropDown = true; + validation.Formula1 = "$B$2:$B$5"; // absolute reference to source list range + + // Save the workbook + string outputPath = "TableWithDropdownValidation.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/add-a-comment-to-the-table-object-describing-its-purpose-and-retrieve-the-comment-text-programmatically.cs b/working-with-tables/add-a-comment-to-the-table-object-describing-its-purpose-and-retrieve-the-comment-text-programmatically.cs new file mode 100644 index 0000000000..3f376fdd1d --- /dev/null +++ b/working-with-tables/add-a-comment-to-the-table-object-describing-its-purpose-and-retrieve-the-comment-text-programmatically.cs @@ -0,0 +1,34 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class ListObjectCommentDemo +{ + 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("ID"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue(100); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue(200); + + // Add a ListObject (table) that covers the data range A1:B3 + int listIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[listIndex]; + + // Set a comment describing the purpose of the table + table.Comment = "This table stores IDs and their corresponding values."; + + // Retrieve the comment text programmatically and display it + Console.WriteLine("Table Comment: " + table.Comment); + + // Save the workbook + workbook.Save("ListObjectWithComment.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/add-a-new-row-to-a-table-and-populate-it-with-values-from-a-dictionary-object.cs b/working-with-tables/add-a-new-row-to-a-table-and-populate-it-with-values-from-a-dictionary-object.cs new file mode 100644 index 0000000000..b9115788f0 --- /dev/null +++ b/working-with-tables/add-a-new-row-to-a-table-and-populate-it-with-values-from-a-dictionary-object.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableExample +{ + class Program + { + 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 header and a couple of data rows to form a table + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Product"); + cells["C1"].PutValue("Price"); + + cells["A2"].PutValue(1); + cells["B2"].PutValue("Laptop"); + cells["C2"].PutValue(999.99m); + + cells["A3"].PutValue(2); + cells["B3"].PutValue("Monitor"); + cells["C3"].PutValue(249.99m); + + // Create a ListObject (Excel table) covering the data range + int tableIndex = worksheet.ListObjects.Add("A1", "C3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Dictionary containing values for the new row + var newRowData = new Dictionary + { + { "ID", 3 }, + { "Product", "Keyboard" }, + { "Price", 49.99m } + }; + + // Determine the row offset for the new row (append at the end) + // DataRange includes the header row, so subtract 1 to get existing data rows count + int newRowOffset = table.DataRange.RowCount - 1; + + // Populate each column using the dictionary values + foreach (KeyValuePair kvp in newRowData) + { + // Find the column index by header name + int columnIndex = -1; + for (int i = 0; i < table.ListColumns.Count; i++) + { + if (string.Equals(table.ListColumns[i].Name, kvp.Key, StringComparison.OrdinalIgnoreCase)) + { + columnIndex = i; + break; + } + } + + // If the column exists, put the value; otherwise ignore + if (columnIndex >= 0) + { + table.PutCellValue(newRowOffset, columnIndex, kvp.Value); + } + } + + // Save the workbook + string outputPath = "TableWithNewRow.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/working-with-tables/add-a-slicer-linked-to-a-table-column-and-configure-it-to-allow-multiselection-for-flexible-filtering.cs b/working-with-tables/add-a-slicer-linked-to-a-table-column-and-configure-it-to-allow-multiselection-for-flexible-filtering.cs new file mode 100644 index 0000000000..00fada4dc9 --- /dev/null +++ b/working-with-tables/add-a-slicer-linked-to-a-table-column-and-configure-it-to-allow-multiselection-for-flexible-filtering.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace AsposeCellsSlicerExample +{ + public class MultiSelectSlicerDemo + { + public static void Run() + { + 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 the 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.TableStyleType = TableStyleType.TableStyleMedium2; + + // Add a slicer linked to the first column ("Category") of the table + // Placed with its upper‑left corner at row 6, column 2 (cell B6) + SlicerCollection slicers = sheet.Slicers; + int slicerIndex = slicers.Add(table, table.ListColumns[0], 6, 2); + Slicer slicer = slicers[slicerIndex]; + + // Configure slicer appearance (optional) + slicer.Caption = "Category Filter"; + slicer.NumberOfColumns = 2; // layout with two columns for easier multi‑selection + + // Use Shape properties instead of obsolete WidthPixel/HeightPixel + slicer.Shape.Width = 200; // width in points + slicer.Shape.Height = 150; // height in points + + // Save the workbook + string outputPath = "MultiSelectSlicerDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + // Entry point required for console application + public static void Main(string[] args) + { + Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/add-a-slicer-linked-to-a-table-column-to-provide-interactive-filtering-in-the-worksheet.cs b/working-with-tables/add-a-slicer-linked-to-a-table-column-to-provide-interactive-filtering-in-the-worksheet.cs new file mode 100644 index 0000000000..062dd779af --- /dev/null +++ b/working-with-tables/add-a-slicer-linked-to-a-table-column-to-provide-interactive-filtering-in-the-worksheet.cs @@ -0,0 +1,51 @@ +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +namespace AsposeCellsSlicerDemo +{ + 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 table (A1:B5) + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Amount"); + sheet.Cells["A2"].PutValue("Food"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["A3"].PutValue("Drink"); + sheet.Cells["B3"].PutValue(80); + sheet.Cells["A4"].PutValue("Food"); + sheet.Cells["B4"].PutValue(150); + sheet.Cells["A5"].PutValue("Snack"); + sheet.Cells["B5"].PutValue(60); + + // Convert the range into a ListObject (table) + // Add table covering A1:B5 (true indicates the range has headers) + int tableIndex = sheet.ListObjects.Add("A1", "B5", true); + ListObject table = sheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; // optional styling + + // Add a slicer linked to the "Category" column of the table + // Use zero‑based row and column indices for the upper‑left corner of the slicer + // Here we place the slicer starting at row 7 (index 6) and column 2 (index 1) + SlicerCollection slicers = sheet.Slicers; + int slicerIndex = slicers.Add(table, table.ListColumns[0], 6, 1); + Slicer slicer = slicers[slicerIndex]; + + // Optional: customize slicer appearance + slicer.Caption = "Category Filter"; + slicer.NumberOfColumns = 1; + slicer.StyleType = SlicerStyleType.SlicerStyleLight1; + slicer.WidthPixel = 150; + slicer.HeightPixel = 120; + + // Save the workbook with the slicer + workbook.Save("SlicerLinkedToTable.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/add-a-totals-row-to-the-table-and-configure-sum-formulas-for-numeric-columns.cs b/working-with-tables/add-a-totals-row-to-the-table-and-configure-sum-formulas-for-numeric-columns.cs new file mode 100644 index 0000000000..634626fb78 --- /dev/null +++ b/working-with-tables/add-a-totals-row-to-the-table-and-configure-sum-formulas-for-numeric-columns.cs @@ -0,0 +1,57 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTotalsRowDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate header row + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["C1"].PutValue("Price"); + + // Populate some sample data (numeric columns are Quantity and Price) + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["C2"].PutValue(0.5); + + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(20); + cells["C3"].PutValue(0.3); + + cells["A4"].PutValue("Orange"); + cells["B4"].PutValue(15); + cells["C4"].PutValue(0.4); + + // Create a table that includes the data range (A1:C4) + int tableIndex = worksheet.ListObjects.Add("A1", "C4", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Enable the totals row for the table + table.ShowTotals = true; + + // Configure sum calculation for each numeric column + // Column 1 (Quantity) + table.ListColumns[1].TotalsCalculation = TotalsCalculation.Sum; + table.ListColumns[1].TotalsRowLabel = "Total Quantity"; + + // Column 2 (Price) + table.ListColumns[2].TotalsCalculation = TotalsCalculation.Sum; + table.ListColumns[2].TotalsRowLabel = "Total Price"; + + // Optionally, you can set a custom label for the first (non‑numeric) column + table.ListColumns[0].TotalsRowLabel = "Grand Total"; + + // Save the workbook + workbook.Save("TableWithTotals.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/after-conversion-attempt-to-apply-a-filter-to-the-former-table-range-and-capture-the-expected-exception.cs b/working-with-tables/after-conversion-attempt-to-apply-a-filter-to-the-former-table-range-and-capture-the-expected-exception.cs new file mode 100644 index 0000000000..1b9a24a7f0 --- /dev/null +++ b/working-with-tables/after-conversion-attempt-to-apply-a-filter-to-the-former-table-range-and-capture-the-expected-exception.cs @@ -0,0 +1,69 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +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 (including a header row) + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + worksheet.Cells["A4"].PutValue(3); + worksheet.Cells["B4"].PutValue("Charlie"); + + // Add a ListObject (table) that covers the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B4", true); + ListObject listObject = worksheet.ListObjects[tableIndex]; + + // Enable auto‑filter for the table and apply a simple filter + listObject.HasAutoFilter = true; + listObject.AutoFilter.Custom(0, FilterOperatorType.GreaterOrEqual, 2); + listObject.AutoFilter.Refresh(); + + // Convert the table back to a normal range + listObject.ConvertToRange(); + + // After conversion the ListObject is removed from the worksheet. + // Attempt to apply a filter using the former ListObject reference. + // This should raise an exception because the object is no longer part of the sheet. + try + { + // The Filter method is obsolete but still callable; it will fail here. + listObject.Filter(); + } + catch (Exception ex) + { + Console.WriteLine("Expected exception caught: " + ex.Message); + } + + // Demonstrate that the worksheet can still apply a filter to the same cell area. + try + { + CellArea filterArea = new CellArea + { + StartRow = 0, // Row 1 (zero‑based) + StartColumn = 0, // Column A + EndRow = 3, // Row 4 + EndColumn = 1 // Column B + }; + worksheet.Filter(filterArea); + Console.WriteLine("Worksheet.Filter applied successfully after conversion."); + } + catch (Exception ex) + { + Console.WriteLine("Worksheet.Filter exception: " + ex.Message); + } + + // Save the workbook to verify the final state + workbook.Save("TableConversionFilterDemo.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/after-converting-a-table-to-a-range-attempt-to-apply-sorting-and-confirm-it-affects-only-the-range.cs b/working-with-tables/after-converting-a-table-to-a-range-attempt-to-apply-sorting-and-confirm-it-affects-only-the-range.cs new file mode 100644 index 0000000000..42564fc5da --- /dev/null +++ b/working-with-tables/after-converting-a-table-to-a-range-attempt-to-apply-sorting-and-confirm-it-affects-only-the-range.cs @@ -0,0 +1,98 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using AsposeRange = Aspose.Cells.Range; + +namespace AsposeCellsExamples +{ + public class TableToRangeSortDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate header row + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + cells["C1"].PutValue("Score"); + cells["D1"].PutValue("Category"); + + // Populate sample data rows + cells["A2"].PutValue(1); cells["B2"].PutValue("Alice"); cells["C2"].PutValue(85); cells["D2"].PutValue("X"); + cells["A3"].PutValue(2); cells["B3"].PutValue("Bob"); cells["C3"].PutValue(92); cells["D3"].PutValue("Y"); + cells["A4"].PutValue(3); cells["B4"].PutValue("Charlie"); cells["C4"].PutValue(78); cells["D4"].PutValue("X"); + cells["A5"].PutValue(4); cells["B5"].PutValue("Diana"); cells["C5"].PutValue(88); cells["D5"].PutValue("Y"); + + // Add a table (ListObject) covering the data range A1:D5 + int tableIndex = sheet.ListObjects.Add("A1", "D5", true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "SampleTable"; + + // Capture the data range of the table (including header) + AsposeRange tableRange = table.DataRange; // includes header row + + // Convert the table to a normal range (the table object will be removed) + table.ConvertToRange(); + + // Verify that the table has been removed + Console.WriteLine("ListObjects count after conversion: " + sheet.ListObjects.Count); + + // Set up the DataSorter to sort by the "Score" column (third column, index 2) + DataSorter sorter = workbook.DataSorter; + sorter.HasHeaders = true; // First row is header + sorter.AddKey(2, SortOrder.Descending); // Sort by column C (Score) descending + + // Define the sort area using the previously captured range address + CellArea sortArea = new CellArea + { + StartRow = tableRange.FirstRow, + StartColumn = tableRange.FirstColumn, + EndRow = tableRange.FirstRow + tableRange.RowCount - 1, + EndColumn = tableRange.FirstColumn + tableRange.ColumnCount - 1 + }; + + // Perform the sort + sorter.Sort(cells, sortArea); + + // Confirm that sorting affected only the defined range + Console.WriteLine("Value in cell E1 (should be empty): '" + cells["E1"].StringValue + "'"); + + // Output the sorted data to console for verification + Console.WriteLine("Sorted data (including header):"); + for (int r = sortArea.StartRow; r <= sortArea.EndRow; r++) + { + for (int c = sortArea.StartColumn; c <= sortArea.EndColumn; c++) + { + Console.Write(cells[r, c].StringValue + "\t"); + } + Console.WriteLine(); + } + + // Save the workbook (overwrite if it already exists) + string outputPath = "TableToRangeSorted.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'"); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine("An error occurred: " + ex.Message); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + TableToRangeSortDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/agents.md b/working-with-tables/agents.md new file mode 100644 index 0000000000..aa71c9d416 --- /dev/null +++ b/working-with-tables/agents.md @@ -0,0 +1,116 @@ +--- +category: working-with-tables +framework: .NET +parent: ../agents.md +version: v2 +--- + +# Persona + +You are a C# developer specializing in Excel tables and structured data using Aspose.Cells for .NET. + +Generate simple, correct, production-quality examples that demonstrate ONE table-related 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; + +--- + +# Key APIs + +- ListObject +- ListObjectCollection +- Worksheet.ListObjects +- ListObject.TableStyleType +- ListColumn + +--- + +# Common Pattern + +1. Create workbook +2. Populate worksheet data +3. Create table from data range +4. Configure table properties +5. Save workbook +6. Print success message + +--- + +# Table Rules + +- Create header rows before creating tables +- Use meaningful column names +- Demonstrate one table feature per example +- Keep sample datasets small and readable + +--- + +# Input Strategy + +- Do NOT rely on external XLSX files +- Generate worksheet 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 table +- Apply table styles +- Add or remove columns +- Show totals row +- Access table data +- Resize table ranges + +--- + +# Common Mistakes + +❌ var workbook = new Workbook(); +✅ Workbook workbook = new Workbook(); + +❌ Create table without header row +✅ Create descriptive column headers first + +❌ Workbook workbook = new Workbook("input.xlsx"); +✅ Workbook workbook = new Workbook(); + +--- + +# Code Simplicity + +- Keep examples concise +- Avoid unnecessary abstractions +- Focus on one table capability per example + +--- + +# General Rules + +Refer to the root agents.md for: +- Boundaries +- Testing requirements +- Build and run instructions diff --git a/working-with-tables/apply-a-builtin-table-style-that-matches-the-workbooks-theme-for-consistent-visual-appearance.cs b/working-with-tables/apply-a-builtin-table-style-that-matches-the-workbooks-theme-for-consistent-visual-appearance.cs new file mode 100644 index 0000000000..d7eb554f5a --- /dev/null +++ b/working-with-tables/apply-a-builtin-table-style-that-matches-the-workbooks-theme-for-consistent-visual-appearance.cs @@ -0,0 +1,70 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class ApplyBuiltinTableStyleDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the table + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["C1"].PutValue("Price"); + + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["C2"].PutValue(0.5); + + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["C3"].PutValue(0.3); + + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(15); + worksheet.Cells["C4"].PutValue(0.8); + + // Add a ListObject (table) that covers the data range + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 2, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Get the collection of built‑in table styles + TableStyleCollection tableStyles = workbook.Worksheets.TableStyles; + + // Choose a built‑in style that aligns with the workbook's theme. + TableStyle builtinStyle = tableStyles.GetBuiltinTableStyle(TableStyleType.TableStyleMedium2); + + // Apply the built‑in style to the table + table.TableStyleName = builtinStyle.Name; + + // Optional: enable additional style features + table.ShowTableStyleFirstColumn = true; + table.ShowTableStyleLastColumn = true; + table.ShowTableStyleRowStripes = true; + table.ShowTableStyleColumnStripes = true; + + // Save the workbook + string outputPath = "AppliedBuiltinTableStyle.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + // Entry point for the application + public static void Main(string[] args) + { + Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-custom-cell-style-to-a-tables-totals-row-to-differentiate-it-visually-from-data-rows.cs b/working-with-tables/apply-a-custom-cell-style-to-a-tables-totals-row-to-differentiate-it-visually-from-data-rows.cs new file mode 100644 index 0000000000..a8a16e05e7 --- /dev/null +++ b/working-with-tables/apply-a-custom-cell-style-to-a-tables-totals-row-to-differentiate-it-visually-from-data-rows.cs @@ -0,0 +1,95 @@ +using System; +using System.Drawing; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class ApplyCustomStyleToTotalsRow + { + public static void Run() + { + 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 (header + 3 data rows) + cells["A1"].PutValue("Product"); + cells["B1"].PutValue("Price"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Orange"); + cells["B3"].PutValue(15); + cells["A4"].PutValue("Banana"); + cells["B4"].PutValue(12); + + // Add a table that includes the data range and enable totals row + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.ShowTotals = true; + + // Set totals calculation for the Price column (second column) + ListColumn priceColumn = table.ListColumns[1]; + priceColumn.TotalsCalculation = TotalsCalculation.Sum; + priceColumn.TotalsRowLabel = "Grand Total"; + + // ------------------------------------------------------------ + // Create a custom table style that will be applied to the totals row + // ------------------------------------------------------------ + const string customStyleName = "MyTotalsStyle"; + + // Add a new table style to the workbook's TableStyles collection + TableStyleCollection tableStyles = workbook.Worksheets.TableStyles; + int styleIdx = tableStyles.AddTableStyle(customStyleName); + TableStyle customTableStyle = tableStyles[styleIdx]; + + // Define the style for the totals row + Style totalsRowStyle = workbook.CreateStyle(); + totalsRowStyle.Pattern = BackgroundType.Solid; + totalsRowStyle.ForegroundColor = Color.LightGoldenrodYellow; // background color + totalsRowStyle.Font.IsBold = true; // bold font + totalsRowStyle.Font.Color = Color.DarkBlue; // font color + + // Associate the style with the TotalRow element of the custom table style + TableStyleElementCollection elements = customTableStyle.TableStyleElements; + int elementIdx = elements.Add(TableStyleElementType.TotalRow); + TableStyleElement totalRowElement = elements[elementIdx]; + totalRowElement.SetElementStyle(totalsRowStyle); + + // Apply the custom table style to the table + table.TableStyleName = customStyleName; + + // ------------------------------------------------------------ + // Save the workbook + // ------------------------------------------------------------ + string outputPath = "TableWithCustomTotalsRowStyle.xlsx"; + + // Ensure the directory exists before saving + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + ApplyCustomStyleToTotalsRow.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-custom-number-format-to-a-numeric-column-in-a-table-to-display-values-as-currency.cs b/working-with-tables/apply-a-custom-number-format-to-a-numeric-column-in-a-table-to-display-values-as-currency.cs new file mode 100644 index 0000000000..1f48eca258 --- /dev/null +++ b/working-with-tables/apply-a-custom-number-format-to-a-numeric-column-in-a-table-to-display-values-as-currency.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class TableCurrencyFormatDemo + { + 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 sheet = workbook.Worksheets[0]; + + // Populate sample data + sheet.Cells["A1"].PutValue("Item"); + sheet.Cells["B1"].PutValue("Amount"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(1234.5); + sheet.Cells["A3"].PutValue("Banana"); + sheet.Cells["B3"].PutValue(5678.9); + sheet.Cells["A4"].PutValue("Cherry"); + sheet.Cells["B4"].PutValue(9012.34); + + // Create a table (ListObject) that includes the data range + // Parameters: first row, first column, last row, last column, hasHeaders + int tableIndex = sheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + // Optional: set a display name for the table (if supported) + // table.DisplayName = "SalesTable"; + + // Define a custom currency number format + Style currencyStyle = workbook.CreateStyle(); + currencyStyle.Custom = "$#,##0.00"; + + // Prepare a StyleFlag to apply only the number format + StyleFlag flag = new StyleFlag { NumberFormat = true }; + + // Determine the range of the numeric column (second column of the table) + // DataRange gives the body of the table without the header row + Aspose.Cells.Range dataRange = table.DataRange; + int firstDataRow = dataRange.FirstRow; // first row of data (excluding header) + int amountColumnIndex = dataRange.FirstColumn + 1; // second column (Amount) + int rowCount = dataRange.RowCount; // number of data rows + + // Create a range that covers the entire Amount column within the table + Aspose.Cells.Range amountRange = sheet.Cells.CreateRange(firstDataRow, amountColumnIndex, rowCount, 1); + + // Apply the custom currency format to the range + amountRange.ApplyStyle(currencyStyle, flag); + + // Save the workbook + string outputPath = "TableCurrencyFormat.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-filter-that-excludes-rows-where-the-date-column-falls-outside-the-current-quarter.cs b/working-with-tables/apply-a-filter-that-excludes-rows-where-the-date-column-falls-outside-the-current-quarter.cs new file mode 100644 index 0000000000..f239ef3a1a --- /dev/null +++ b/working-with-tables/apply-a-filter-that-excludes-rows-where-the-date-column-falls-outside-the-current-quarter.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsFilterExample +{ + 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 with a header and several dates + sheet.Cells["A1"].PutValue("Date"); + sheet.Cells["A2"].PutValue(new DateTime(2023, 1, 15)); + sheet.Cells["A3"].PutValue(new DateTime(2023, 2, 20)); + sheet.Cells["A4"].PutValue(new DateTime(2023, 3, 10)); + sheet.Cells["A5"].PutValue(new DateTime(2023, 4, 5)); + sheet.Cells["A6"].PutValue(new DateTime(2023, 5, 12)); + sheet.Cells["A7"].PutValue(new DateTime(2023, 6, 30)); + + // Define the auto‑filter range (including header and data rows) + sheet.AutoFilter.Range = "A1:A7"; + + // Apply a dynamic filter to keep only dates that belong to the current quarter + // This automatically hides rows whose dates are outside the current quarter + sheet.AutoFilter.DynamicFilter(0, DynamicFilterType.ThisQuarter); + + // Refresh the filter to apply the changes + sheet.AutoFilter.Refresh(); + + // Save the workbook + workbook.Save("FilteredByCurrentQuarter.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-filter-that-selects-rows-where-the-status-column-equals-completed-and-hide-the-rest.cs b/working-with-tables/apply-a-filter-that-selects-rows-where-the-status-column-equals-completed-and-hide-the-rest.cs new file mode 100644 index 0000000000..a6b2b74014 --- /dev/null +++ b/working-with-tables/apply-a-filter-that-selects-rows-where-the-status-column-equals-completed-and-hide-the-rest.cs @@ -0,0 +1,58 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsFilterExample +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // ----- Sample data (Header + rows) ----- + // Header row + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Task"); + sheet.Cells["C1"].PutValue("Status"); + + // Data rows + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Design"); + sheet.Cells["C2"].PutValue("Completed"); + + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Development"); + sheet.Cells["C3"].PutValue("In Progress"); + + sheet.Cells["A4"].PutValue(4); + sheet.Cells["B4"].PutValue("Testing"); + sheet.Cells["C4"].PutValue("Completed"); + + sheet.Cells["A5"].PutValue(5); + sheet.Cells["B5"].PutValue("Deployment"); + sheet.Cells["C5"].PutValue("Pending"); + + // ----- Apply AutoFilter ----- + // Define the range that contains the header and data rows + sheet.AutoFilter.Range = "A1:C5"; + + // Filter the 'Status' column (index 2, i.e., column C) for the value "Completed" + sheet.AutoFilter.Filter(2, "Completed"); + + // Refresh the filter to hide rows that do not meet the criteria + sheet.AutoFilter.Refresh(); + + // Optional: verify which rows are hidden + for (int row = 1; row <= sheet.Cells.MaxDataRow; row++) + { + bool hidden = sheet.Cells.IsRowHidden(row); + Console.WriteLine($"Row {row + 1} hidden: {hidden}"); + } + + // Save the workbook + workbook.Save("FilteredByStatus.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-predefined-table-style-to-the-created-table-and-preserve-the-original-formatting.cs b/working-with-tables/apply-a-predefined-table-style-to-the-created-table-and-preserve-the-original-formatting.cs new file mode 100644 index 0000000000..7e21de4aa0 --- /dev/null +++ b/working-with-tables/apply-a-predefined-table-style-to-the-created-table-and-preserve-the-original-formatting.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableStyleDemo +{ + 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 (5 columns x 10 rows) + for (int col = 0; col < 5; col++) + { + cells[0, col].PutValue($"Header {col + 1}"); + for (int row = 1; row < 10; row++) + { + cells[row, col].PutValue(row * (col + 1)); + } + } + + // Add a table that covers the populated range + int tableIndex = sheet.ListObjects.Add(0, 0, 9, 4, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Retrieve a predefined (built‑in) table style + TableStyleCollection styleCollection = workbook.Worksheets.TableStyles; + TableStyle predefinedStyle = styleCollection.GetBuiltinTableStyle(TableStyleType.TableStyleMedium2); + + // Apply the predefined style to the table + table.TableStyleName = predefinedStyle.Name; + + // Preserve the original cell formatting by re‑applying the style to the table's range + // (ApplyStyleToRange respects existing explicit formatting where possible) + table.ApplyStyleToRange(); + + // Optionally show first/last column styling + table.ShowTableStyleFirstColumn = true; + table.ShowTableStyleLastColumn = true; + + // Save the workbook + workbook.Save("PredefinedTableStylePreserved.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-table-style-that-uses-alternating-row-colors-to-improve-readability-of-large-data-sets.cs b/working-with-tables/apply-a-table-style-that-uses-alternating-row-colors-to-improve-readability-of-large-data-sets.cs new file mode 100644 index 0000000000..715cf0b641 --- /dev/null +++ b/working-with-tables/apply-a-table-style-that-uses-alternating-row-colors-to-improve-readability-of-large-data-sets.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class ApplyAlternatingRowColors +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data (header + 100 rows) + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Value"); + for (int i = 2; i <= 101; i++) + { + sheet.Cells[i - 1, 0].PutValue(i - 1); // ID + sheet.Cells[i - 1, 1].PutValue($"Item {i - 1}"); // Name + sheet.Cells[i - 1, 2].PutValue((i - 1) * 10); // Value + } + + // Convert the range A1:C101 into a table (ListObject) + int tableIndex = sheet.ListObjects.Add(0, 0, 100, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Apply a built‑in table style that includes row stripes + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Enable alternating row stripe formatting + table.ShowTableStyleRowStripes = true; + + // Save the workbook with the applied style + workbook.Save("AlternatingRowColors.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/apply-a-unique-index-to-a-table-column-to-enforce-data-uniqueness-during-data-entry.cs b/working-with-tables/apply-a-unique-index-to-a-table-column-to-enforce-data-uniqueness-during-data-entry.cs new file mode 100644 index 0000000000..945344b667 --- /dev/null +++ b/working-with-tables/apply-a-unique-index-to-a-table-column-to-enforce-data-uniqueness-during-data-entry.cs @@ -0,0 +1,41 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Saving; + +class ApplyUniqueIndexDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Add header row + sheet.Cells["A1"].PutValue("EmployeeID"); + sheet.Cells["B1"].PutValue("Name"); + + // Add sample data (including a duplicate ID to illustrate uniqueness enforcement) + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["A4"].PutValue(1); // Duplicate ID + sheet.Cells["B4"].PutValue("Charlie"); + + // Configure SQL script save options: + // - TableName: name of the generated table + // - CreateTable: generate CREATE TABLE statement + // - HasHeaderRow: first row contains column names + // - PrimaryKey: set column index 0 (EmployeeID) as the primary key (unique index) + SqlScriptSaveOptions saveOptions = new SqlScriptSaveOptions + { + TableName = "Employees", + CreateTable = true, + HasHeaderRow = true, + PrimaryKey = 0 + }; + + // Save the workbook as an SQL script; the script will include a PRIMARY KEY constraint on EmployeeID + workbook.Save("Employees.sql", saveOptions); + } +} \ No newline at end of file diff --git a/working-with-tables/apply-conditional-formatting-to-a-table-column-that-highlights-cells-exceeding-a-defined-numeric-threshold.cs b/working-with-tables/apply-conditional-formatting-to-a-table-column-that-highlights-cells-exceeding-a-defined-numeric-threshold.cs new file mode 100644 index 0000000000..2297d50c47 --- /dev/null +++ b/working-with-tables/apply-conditional-formatting-to-a-table-column-that-highlights-cells-exceeding-a-defined-numeric-threshold.cs @@ -0,0 +1,57 @@ +using System; +using System.Drawing; +using Aspose.Cells; + +namespace ConditionalFormattingExample +{ + 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 numeric data in column B (index 1) rows 1-20 + for (int row = 0; row < 20; row++) + { + sheet.Cells[row, 1].PutValue(row * 5); // Example values: 0,5,10,... + } + + // Define the range for the column to which the conditional format will be applied + // Here we target column B from row 0 to row 19 (A1 style: B1:B20) + CellArea columnArea = new CellArea + { + StartRow = 0, + EndRow = 19, + StartColumn = 1, + EndColumn = 1 + }; + + // Add a new conditional formatting collection to the worksheet + int cfIndex = sheet.ConditionalFormattings.Add(); + FormatConditionCollection conditions = sheet.ConditionalFormattings[cfIndex]; + + // Associate the defined range with the conditional formatting collection + conditions.AddArea(columnArea); + + // Define the numeric threshold; cells greater than this value will be highlighted + const string threshold = "50"; + + // Add a CellValue condition: GreaterThan the threshold + int conditionIdx = conditions.AddCondition( + FormatConditionType.CellValue, + OperatorType.GreaterThan, + threshold, + null); + + // Retrieve the created condition and set its formatting style + FormatCondition condition = conditions[conditionIdx]; + condition.Style.BackgroundColor = Color.Yellow; // Highlight with yellow background + condition.Style.Font.Color = Color.Black; // Optional: set font color for readability + + // Save the workbook to a file + workbook.Save("ConditionalFormatting_ColumnThreshold.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/apply-conditional-formatting-to-highlight-duplicate-values-within-a-specific-table-column-for-data-quality-checks.cs b/working-with-tables/apply-conditional-formatting-to-highlight-duplicate-values-within-a-specific-table-column-for-data-quality-checks.cs new file mode 100644 index 0000000000..02d9cd7cee --- /dev/null +++ b/working-with-tables/apply-conditional-formatting-to-highlight-duplicate-values-within-a-specific-table-column-for-data-quality-checks.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using System.Drawing; + +class HighlightDuplicates +{ + static void Main() + { + // 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 in column B (index 1) + string[] sampleData = { "Apple", "Banana", "Apple", "Orange", "Banana", "Grape" }; + for (int i = 0; i < sampleData.Length; i++) + { + cells[i, 1].PutValue(sampleData[i]); // B column + } + + // Add a conditional formatting collection to the worksheet + int cfIndex = worksheet.ConditionalFormattings.Add(); + FormatConditionCollection conditions = worksheet.ConditionalFormattings[cfIndex]; + + // Define the range that covers the populated cells in column B + CellArea range = new CellArea + { + StartRow = 0, + EndRow = sampleData.Length - 1, + StartColumn = 1, + EndColumn = 1 + }; + conditions.AddArea(range); + + // Add a condition that highlights duplicate values + int dupConditionIdx = conditions.AddCondition(FormatConditionType.DuplicateValues); + FormatCondition dupCondition = conditions[dupConditionIdx]; + + // Set the visual style for duplicate cells (e.g., yellow background) + dupCondition.Style.BackgroundColor = Color.Yellow; + + // Save the workbook with the applied conditional formatting + workbook.Save("DuplicateHighlight.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/apply-tabletorangeoptionslastrow-to-keep-formatting-through-row-fifteen-before-converting-the-table-to-a-range.cs b/working-with-tables/apply-tabletorangeoptionslastrow-to-keep-formatting-through-row-fifteen-before-converting-the-table-to-a-range.cs new file mode 100644 index 0000000000..7c95267ba3 --- /dev/null +++ b/working-with-tables/apply-tabletorangeoptionslastrow-to-keep-formatting-through-row-fifteen-before-converting-the-table-to-a-range.cs @@ -0,0 +1,40 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // 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 (20 rows, 5 columns) + for (int row = 0; row < 20; row++) + { + for (int col = 0; col < 5; col++) + { + cells[row, col].PutValue($"Data {row}-{col}"); + } + } + + // Add a table that initially spans rows 0‑19 and columns 0‑4 + int tableIndex = worksheet.ListObjects.Add(0, 0, 19, 4, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Set TableToRangeOptions to keep formatting through row 15 (zero‑based index 14) + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = 14 // rows 0‑14 will be converted; rows 15‑19 remain as part of the table + }; + + // Convert the table to a range using the specified options + table.ConvertToRange(options); + + // Save the workbook + workbook.Save("TableToRange_With_LastRow.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/apply-tabletorangeoptionslastrow-to-retain-formatting-for-the-header-and-first-data-row-only-before-conversion.cs b/working-with-tables/apply-tabletorangeoptionslastrow-to-retain-formatting-for-the-header-and-first-data-row-only-before-conversion.cs new file mode 100644 index 0000000000..b5b6f81162 --- /dev/null +++ b/working-with-tables/apply-tabletorangeoptionslastrow-to-retain-formatting-for-the-header-and-first-data-row-only-before-conversion.cs @@ -0,0 +1,45 @@ +using Aspose.Cells; +using Aspose.Cells.Tables; + +class TableToRangeHeaderAndFirstRowDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate header row (row 0) + cells[0, 0].PutValue("Header1"); + cells[0, 1].PutValue("Header2"); + + // Populate first data row (row 1) + cells[1, 0].PutValue("Data1"); + cells[1, 1].PutValue(100); + + // Populate additional data rows (these will be excluded from conversion) + cells[2, 0].PutValue("Data2"); + cells[2, 1].PutValue(200); + cells[3, 0].PutValue("Data3"); + cells[3, 1].PutValue(300); + + // Add a table that spans rows 0‑3 and columns 0‑1 + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; // optional styling + + // Configure conversion options to retain only the header and the first data row + TableToRangeOptions options = new TableToRangeOptions + { + // LastRow is zero‑based; setting it to 1 keeps rows 0 (header) and 1 (first data row) + LastRow = 1 + }; + + // Convert the table to a range using the specified options + table.ConvertToRange(options); + + // Save the workbook + workbook.Save("TableToRangeHeaderAndFirstRow.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/autofit-all-columns-of-a-table-to-match-the-longest-cell-content-for-optimal-display.cs b/working-with-tables/autofit-all-columns-of-a-table-to-match-the-longest-cell-content-for-optimal-display.cs new file mode 100644 index 0000000000..0557f1698a --- /dev/null +++ b/working-with-tables/autofit-all-columns-of-a-table-to-match-the-longest-cell-content-for-optimal-display.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsAutoFitDemo +{ + public class AutoFitColumnsExample + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Product Description"); + worksheet.Cells["C1"].PutValue("Price"); + + worksheet.Cells["A2"].PutValue(101); + worksheet.Cells["B2"].PutValue("Compact widget"); + worksheet.Cells["C2"].PutValue(12.5); + + worksheet.Cells["A3"].PutValue(102); + worksheet.Cells["B3"].PutValue("Advanced multi-purpose widget with extended features and a very long description"); + worksheet.Cells["C3"].PutValue(199.99); + + // Auto‑fit all columns so each column width matches its longest cell content + worksheet.AutoFitColumns(); + + // Save the workbook + string outputPath = "AutoFitColumnsResult.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Application entry point + public class Program + { + public static void Main(string[] args) + { + AutoFitColumnsExample.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/batch-process-multiple-worksheets-converting-each-table-to-a-range-and-saving-each-workbook-as-ods.cs b/working-with-tables/batch-process-multiple-worksheets-converting-each-table-to-a-range-and-saving-each-workbook-as-ods.cs new file mode 100644 index 0000000000..9114ec6c34 --- /dev/null +++ b/working-with-tables/batch-process-multiple-worksheets-converting-each-table-to-a-range-and-saving-each-workbook-as-ods.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Ods; + +namespace BatchTableToRangeToOds +{ + class Program + { + static void Main() + { + // Folder containing the source Excel workbooks + string sourceFolder = @"C:\InputWorkbooks"; + + // Folder where the ODS files will be saved + string outputFolder = @"C:\OutputOds"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Process each Excel file in the source folder + foreach (string excelFile in Directory.GetFiles(sourceFolder, "*.xlsx")) + { + // Load the workbook using Aspose.Cells (create/load rule) + Workbook workbook = new Workbook(excelFile); + + // Iterate through all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + // Iterate through all tables (ListObjects) in the worksheet + foreach (ListObject table in sheet.ListObjects) + { + // Convert the table to a normal range (use provided ConvertToRange method) + table.ConvertToRange(); + } + } + + // Prepare ODS save options (optional: ignore pivot tables) + OdsSaveOptions odsOptions = new OdsSaveOptions + { + IgnorePivotTables = true + }; + + // Build the output file path with .ods extension + string odsFileName = Path.GetFileNameWithoutExtension(excelFile) + ".ods"; + string odsPath = Path.Combine(outputFolder, odsFileName); + + // Save the modified workbook as ODS (save rule) + workbook.Save(odsPath, odsOptions); + + Console.WriteLine($"Converted '{excelFile}' to ODS: '{odsPath}'"); + } + + Console.WriteLine("Batch processing completed."); + } + } +} \ No newline at end of file diff --git a/working-with-tables/calculate-a-running-total-column-within-a-table-using-a-formula-that-references-previous-rows.cs b/working-with-tables/calculate-a-running-total-column-within-a-table-using-a-formula-that-references-previous-rows.cs new file mode 100644 index 0000000000..a8cebf881e --- /dev/null +++ b/working-with-tables/calculate-a-running-total-column-within-a-table-using-a-formula-that-references-previous-rows.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class RunningTotalInTable +{ + 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 ----- + // Header row + cells["A1"].PutValue("Amount"); + cells["B1"].PutValue("Running Total"); + + // Sample amounts (rows 2‑6) + double[] amounts = { 100, 150, 200, 250, 300 }; + for (int i = 0; i < amounts.Length; i++) + { + cells[i + 1, 0].PutValue(amounts[i]); // Column A + } + + // ----- Create a table that includes both columns ----- + // Table range: A1:B6 (header + 5 data rows) + int tableIndex = sheet.ListObjects.Add(0, 0, amounts.Length, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.ShowTotals = false; // totals row not required + + // ----- Set running total formula for each data row ----- + // Use A1‑style formulas referencing the worksheet cells directly. + for (int i = 0; i < amounts.Length; i++) + { + int excelRow = i + 2; // Excel rows start at 1; row 2 is first data row + string formula = $"=A{excelRow}+IFERROR(B{excelRow - 1},0)"; + cells[excelRow - 1, 1].Formula = formula; // Column B (index 1) + } + + // Calculate all formulas so the running totals are materialized + workbook.CalculateFormula(); + + // ----- Save the workbook ----- + string outputPath = "RunningTotalTable.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/working-with-tables/change-the-table-style-to-a-custom-xmldefined-style-to-meet-corporate-branding-guidelines.cs b/working-with-tables/change-the-table-style-to-a-custom-xmldefined-style-to-meet-corporate-branding-guidelines.cs new file mode 100644 index 0000000000..83c5234b6d --- /dev/null +++ b/working-with-tables/change-the-table-style-to-a-custom-xmldefined-style-to-meet-corporate-branding-guidelines.cs @@ -0,0 +1,110 @@ +using System; +using System.Drawing; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace CorporateBranding +{ + public class TableStyleDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for the table + cells["A1"].PutValue("Product"); + cells["B1"].PutValue("Category"); + cells["C1"].PutValue("Price"); + for (int i = 2; i <= 6; i++) + { + cells[$"A{i}"].PutValue($"Item{i - 1}"); + cells[$"B{i}"].PutValue("General"); + cells[$"C{i}"].PutValue(10 * i); + } + + // ----------------------------------------------------------------- + // Create a custom table style that follows corporate branding guidelines + // ----------------------------------------------------------------- + string corporateStyleName = "CorporateBrandStyle"; + + // Add a new custom table style to the workbook's table style collection + TableStyleCollection tableStyles = workbook.Worksheets.TableStyles; + int styleIndex = tableStyles.AddTableStyle(corporateStyleName); + TableStyle corporateStyle = tableStyles[styleIndex]; + + // Access the collection of style elements for the custom style + TableStyleElementCollection elements = corporateStyle.TableStyleElements; + + // ------------------------------------------------- + // Header Row style (e.g., dark background, white bold text) + // ------------------------------------------------- + Style headerStyle = workbook.CreateStyle(); + headerStyle.Pattern = BackgroundType.Solid; + headerStyle.BackgroundColor = Color.FromArgb(0, 70, 127); // corporate dark blue + headerStyle.Font.Color = Color.White; + headerStyle.Font.IsBold = true; + headerStyle.Font.Size = 12; + elements.Add(TableStyleElementType.HeaderRow); + TableStyleElement headerElement = elements[TableStyleElementType.HeaderRow]; + headerElement.SetElementStyle(headerStyle); + + // ------------------------------------------------- + // First Column style (e.g., light gray background) + // ------------------------------------------------- + Style firstColStyle = workbook.CreateStyle(); + firstColStyle.Pattern = BackgroundType.Solid; + firstColStyle.BackgroundColor = Color.FromArgb(224, 224, 224); // light gray + firstColStyle.Font.IsBold = true; + elements.Add(TableStyleElementType.FirstColumn); + TableStyleElement firstColElement = elements[TableStyleElementType.FirstColumn]; + firstColElement.SetElementStyle(firstColStyle); + + // ------------------------------------------------- + // Whole Table style (e.g., thin borders with corporate color) + // ------------------------------------------------- + Style wholeTableStyle = workbook.CreateStyle(); + wholeTableStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; + wholeTableStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; + wholeTableStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; + wholeTableStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; + wholeTableStyle.Borders[BorderType.LeftBorder].Color = Color.FromArgb(0, 70, 127); + wholeTableStyle.Borders[BorderType.RightBorder].Color = Color.FromArgb(0, 70, 127); + wholeTableStyle.Borders[BorderType.TopBorder].Color = Color.FromArgb(0, 70, 127); + wholeTableStyle.Borders[BorderType.BottomBorder].Color = Color.FromArgb(0, 70, 127); + elements.Add(TableStyleElementType.WholeTable); + TableStyleElement wholeTableElement = elements[TableStyleElementType.WholeTable]; + wholeTableElement.SetElementStyle(wholeTableStyle); + + // ------------------------------------------------- + // Create a ListObject (table) that uses the custom style + // ------------------------------------------------- + int tableIndex = sheet.ListObjects.Add(0, 0, 5, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.TableStyleName = corporateStyleName; + table.ShowTableStyleFirstColumn = true; // ensure first column style is visible + table.ShowTableStyleRowStripes = true; // optional: add row stripes for readability + + // Save the workbook + string outputPath = "CorporateBrandTableStyle.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + // Entry point for the console application + public static void Main(string[] args) + { + Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/clear-all-filters-applied-to-a-table-restoring-the-full-dataset-visibility-for-analysis.cs b/working-with-tables/clear-all-filters-applied-to-a-table-restoring-the-full-dataset-visibility-for-analysis.cs new file mode 100644 index 0000000000..67603002d7 --- /dev/null +++ b/working-with-tables/clear-all-filters-applied-to-a-table-restoring-the-full-dataset-visibility-for-analysis.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class ClearAllTableFilters +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data with a header row + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Charlie"); + + // Add a ListObject (table) which includes an auto‑filter by default + int tableIndex = sheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Apply a filter to demonstrate that a filter exists + table.AutoFilter.AddFilter(1, "Bob"); + table.AutoFilter.Refresh(); + + // Remove the auto‑filter, clearing all filters applied to the table + table.RemoveAutoFilter(); + + // Save the workbook + workbook.Save("ClearAllTableFilters.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/configure-a-query-table-to-use-windows-authentication-for-connecting-to-a-sql-server-data-source.cs b/working-with-tables/configure-a-query-table-to-use-windows-authentication-for-connecting-to-a-sql-server-data-source.cs new file mode 100644 index 0000000000..c5b95d22f1 --- /dev/null +++ b/working-with-tables/configure-a-query-table-to-use-windows-authentication-for-connecting-to-a-sql-server-data-source.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +namespace AsposeCellsQueryTableWindowsAuth +{ + class Program + { + static void Main() + { + try + { + const string templatePath = "TemplateWithQueryTable.xlsx"; + const string outputPath = "OutputWithWindowsAuth.xlsx"; + + // Verify that the template file exists before attempting to load it. + if (!File.Exists(templatePath)) + { + Console.WriteLine($"Template file not found: {Path.GetFullPath(templatePath)}"); + return; + } + + // Load the workbook that already contains a query table. + Workbook workbook = new Workbook(templatePath); + + // Access the first worksheet (adjust index if needed). + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure the worksheet has at least one query table. + if (sheet.QueryTables.Count == 0) + { + Console.WriteLine("No query tables found in the worksheet."); + return; + } + + // Get the first query table. + QueryTable queryTable = sheet.QueryTables[0]; + + // The query table is linked to an external DB connection. + if (queryTable.ExternalConnection is DBConnection dbConnection) + { + // Set the connection string for SQL Server (Windows Authentication). + dbConnection.ConnectionString = + "Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=SSPI;"; + + // Specify that the authentication method is Windows (Integrated). + dbConnection.CredentialsMethodType = CredentialsMethodType.Integrated; + + Console.WriteLine("Query table connection configured to use Windows authentication."); + } + else + { + Console.WriteLine("The external connection is not a DBConnection."); + return; + } + + // Save the modified workbook. + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to: {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/convert-a-query-table-into-a-regular-worksheet-table-retaining-its-data-and-formatting-attributes.cs b/working-with-tables/convert-a-query-table-into-a-regular-worksheet-table-retaining-its-data-and-formatting-attributes.cs new file mode 100644 index 0000000000..56653f68c1 --- /dev/null +++ b/working-with-tables/convert-a-query-table-into-a-regular-worksheet-table-retaining-its-data-and-formatting-attributes.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsQueryTableConversion +{ + class Program + { + static void Main() + { + try + { + // ---------- Create a new workbook ---------- + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // ---------- Populate sample data ---------- + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + + // ---------- Create a ListObject (table) ---------- + // In a real scenario this ListObject would be linked to a QueryTable + int loIndex = sheet.ListObjects.Add("A1", "B3", true); + ListObject listObject = sheet.ListObjects[loIndex]; + + // For demonstration, assume the ListObject has an associated QueryTable + // (In practice this occurs when the table is created from an external data source) + QueryTable qt = listObject.QueryTable; + + if (qt != null) + { + // Preserve existing formatting during conversion + qt.PreserveFormatting = true; + + // Capture the current range of the ListObject + Aspose.Cells.Range dataRange = listObject.DataRange; + int firstRow = dataRange.FirstRow; + int firstColumn = dataRange.FirstColumn; + int lastRow = firstRow + dataRange.RowCount - 1; + int lastColumn = firstColumn + dataRange.ColumnCount - 1; + + // Convert the ListObject (which contains the QueryTable) to a plain range + listObject.ConvertToRange(); + + // Add a new regular ListObject (worksheet table) on the same range + int newLoIndex = sheet.ListObjects.Add(firstRow, firstColumn, lastRow, lastColumn, true); + ListObject newTable = sheet.ListObjects[newLoIndex]; + + // Example: set a table style + newTable.TableStyleType = TableStyleType.TableStyleMedium9; + } + else + { + Console.WriteLine("No QueryTable associated with the ListObject. No conversion performed."); + } + + // ---------- Save the workbook ---------- + string outputPath = "ConvertedQueryTable.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/working-with-tables/convert-a-table-to-a-range-and-copy-the-resulting-range-to-another-worksheet-using-rangecopy.cs b/working-with-tables/convert-a-table-to-a-range-and-copy-the-resulting-range-to-another-worksheet-using-rangecopy.cs new file mode 100644 index 0000000000..9088d493ee --- /dev/null +++ b/working-with-tables/convert-a-table-to-a-range-and-copy-the-resulting-range-to-another-worksheet-using-rangecopy.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using AsposeRange = Aspose.Cells.Range; + +public class TableToRangeCopyDemo +{ + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet (source) + Workbook workbook = new Workbook(); + Worksheet srcSheet = workbook.Worksheets[0]; + srcSheet.Name = "Source"; + + // Populate sample data for the table + srcSheet.Cells["A1"].PutValue("ID"); + srcSheet.Cells["B1"].PutValue("Name"); + srcSheet.Cells["A2"].PutValue(1); + srcSheet.Cells["B2"].PutValue("John"); + srcSheet.Cells["A3"].PutValue(2); + srcSheet.Cells["B3"].PutValue("Mary"); + + // Add a ListObject (table) covering the data range A1:B3 + int tableIdx = srcSheet.ListObjects.Add("A1", "B3", true); + ListObject table = srcSheet.ListObjects[tableIdx]; + + // Determine the size of the table + int startRow = table.StartRow; + int startCol = table.StartColumn; + int rowCount = table.EndRow - table.StartRow + 1; + int colCount = table.EndColumn - table.StartColumn + 1; + + // Create a Range object that represents the table area (before conversion) + AsposeRange sourceRange = srcSheet.Cells.CreateRange(startRow, startCol, rowCount, colCount); + + // Convert the table to a normal range (the ListObject is removed) + table.ConvertToRange(); + + // Add a destination worksheet + Worksheet destSheet = workbook.Worksheets[workbook.Worksheets.Add()]; + destSheet.Name = "Destination"; + + // Create a destination range with the same dimensions starting at A1 + AsposeRange destRange = destSheet.Cells.CreateRange(0, 0, rowCount, colCount); + + // Copy the source range (now a plain range) to the destination range + sourceRange.Copy(destRange); + + // Define output file path + string outputPath = "TableToRangeCopyDemo.xlsx"; + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved as {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} + +// To execute the demo +class Program +{ + static void Main() + { + TableToRangeCopyDemo.Run(); + } +} \ No newline at end of file diff --git a/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-first-three-rows-then-save-as-ods.cs b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-first-three-rows-then-save-as-ods.cs new file mode 100644 index 0000000000..b6e6f2094c --- /dev/null +++ b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-first-three-rows-then-save-as-ods.cs @@ -0,0 +1,59 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Ods; + +namespace AsposeCellsTableToRangeOds +{ + 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 (5 rows, 3 columns) + // Header row + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Score"); + + // Data rows + for (int row = 2; row <= 5; row++) + { + sheet.Cells[row - 1, 0].PutValue(row - 1); // ID + sheet.Cells[row - 1, 1].PutValue($"Person {row - 1}"); // Name + sheet.Cells[row - 1, 2].PutValue((row - 1) * 10); // Score + } + + // Apply formatting to the first three rows (header + first two data rows) + Style boldStyle = workbook.CreateStyle(); + boldStyle.Font.IsBold = true; + StyleFlag flag = new StyleFlag(); + flag.FontBold = true; + + // Apply to rows 0,1,2 (zero‑based) + sheet.Cells.Rows[0].ApplyStyle(boldStyle, flag); + sheet.Cells.Rows[1].ApplyStyle(boldStyle, flag); + sheet.Cells.Rows[2].ApplyStyle(boldStyle, flag); + + // Add a ListObject (table) that covers the whole data range A1:C5 + int tableIndex = sheet.ListObjects.Add("A1", "C5", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Convert only the first three rows of the table to a normal range, + // preserving the formatting applied above. + TableToRangeOptions options = new TableToRangeOptions + { + // Row indices are zero‑based; 2 corresponds to the third row. + LastRow = 2 + }; + table.ConvertToRange(options); + + // Save the workbook as ODS using default OdsSaveOptions + OdsSaveOptions odsOptions = new OdsSaveOptions(); + workbook.Save("TableConvertedToRange.ods", odsOptions); + } + } +} \ No newline at end of file diff --git a/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-header-row-only-then-save-as-ods.cs b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-header-row-only-then-save-as-ods.cs new file mode 100644 index 0000000000..df5e7ce753 --- /dev/null +++ b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-for-the-header-row-only-then-save-as-ods.cs @@ -0,0 +1,50 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Ods; + +namespace AsposeCellsTableToRangeOds +{ + 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 + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + + // Create a table (ListObject) that includes the header row + int tableIndex = sheet.ListObjects.Add("A1", "B3", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Apply formatting to the header row only + Style headerStyle = workbook.CreateStyle(); + headerStyle.Font.IsBold = true; + headerStyle.ForegroundColor = System.Drawing.Color.LightGray; + headerStyle.Pattern = BackgroundType.Solid; + + sheet.Cells["A1"].SetStyle(headerStyle); + sheet.Cells["B1"].SetStyle(headerStyle); + + // Convert the table to a normal range while keeping the header formatting + table.ConvertToRange(); + + // Prepare ODS save options (optional: set generator type) + OdsSaveOptions saveOptions = new OdsSaveOptions + { + GeneratorType = OdsGeneratorType.LibreOffice + }; + + // Save the workbook as ODS + workbook.Save("TableConvertedToRange.ods", saveOptions); + } + } +} \ No newline at end of file diff --git a/working-with-tables/convert-a-table-to-a-range-preserving-formatting-up-to-the-last-data-row-then-save-as-ods.cs b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-up-to-the-last-data-row-then-save-as-ods.cs new file mode 100644 index 0000000000..08c85d6455 --- /dev/null +++ b/working-with-tables/convert-a-table-to-a-range-preserving-formatting-up-to-the-last-data-row-then-save-as-ods.cs @@ -0,0 +1,54 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Ods; // Namespace for OdsSaveOptions (if needed) + +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 (including a header row) + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Score"); + + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["C2"].PutValue(85); + + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + sheet.Cells["C3"].PutValue(92); + + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Peter"); + sheet.Cells["C4"].PutValue(78); + + sheet.Cells["A5"].PutValue(4); + sheet.Cells["B5"].PutValue("Lucy"); + sheet.Cells["C5"].PutValue(88); + + // Add a ListObject (table) that covers the data range A1:C5 + int tableIndex = sheet.ListObjects.Add("A1", "C5", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Apply a built‑in table style (optional, demonstrates formatting preservation) + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Convert the table to a normal range, preserving formatting up to the last data row. + // The last data row index is 4 (zero‑based, corresponds to row 5 in Excel). + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = 4 + }; + table.ConvertToRange(options); + + // Save the workbook as an ODS file using default OdsSaveOptions. + OdsSaveOptions saveOptions = new OdsSaveOptions(); + workbook.Save("ConvertedTable.ods", saveOptions); + } +} \ No newline at end of file diff --git a/working-with-tables/convert-a-table-to-a-range-retaining-formatting-only-for-the-first-five-rows-then-save-as-ods.cs b/working-with-tables/convert-a-table-to-a-range-retaining-formatting-only-for-the-first-five-rows-then-save-as-ods.cs new file mode 100644 index 0000000000..2b2a648cd0 --- /dev/null +++ b/working-with-tables/convert-a-table-to-a-range-retaining-formatting-only-for-the-first-five-rows-then-save-as-ods.cs @@ -0,0 +1,46 @@ +using System; +using System.Drawing; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Ods; + +class ConvertTableToRangeExample +{ + 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 (10 rows, 3 columns) + for (int row = 0; row < 10; row++) + { + cells[row, 0].PutValue($"ID {row + 1}"); + cells[row, 1].PutValue($"Name {row + 1}"); + cells[row, 2].PutValue(row * 10); + } + + // Apply a style to the whole sheet (so formatting exists on all rows) + Style style = workbook.CreateStyle(); + style.Font.Color = Color.Blue; + style.Font.IsBold = true; + sheet.Cells.ApplyStyle(style, new StyleFlag { FontColor = true, FontBold = true }); + + // Add a table that covers the data (including header row) + int tableIndex = sheet.ListObjects.Add(0, 0, 9, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Convert the table to a range, keeping only the first five rows (0‑4) + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = 4 // zero‑based index; rows 0‑4 correspond to the first five rows + }; + table.ConvertToRange(options); + + // Save the workbook as ODS + OdsSaveOptions saveOptions = new OdsSaveOptions(); + workbook.Save("TableConverted.ods", saveOptions); + } +} \ No newline at end of file diff --git a/working-with-tables/convert-the-existing-list-object-into-a-structured-table-to-leverage-advanced-table-features.cs b/working-with-tables/convert-the-existing-list-object-into-a-structured-table-to-leverage-advanced-table-features.cs new file mode 100644 index 0000000000..b247c00e53 --- /dev/null +++ b/working-with-tables/convert-the-existing-list-object-into-a-structured-table-to-leverage-advanced-table-features.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // Load an existing workbook that contains raw data + Workbook workbook = new Workbook("input.xlsx"); + Worksheet worksheet = workbook.Worksheets[0]; + + // Define the range that holds the data (including header row) + // Adjust the range as needed for your source data + string startCell = "A1"; + string endCell = "C5"; + + // Convert the range into a structured table (ListObject) + int tableIndex = worksheet.ListObjects.Add(startCell, endCell, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Configure table properties to leverage advanced features + table.DisplayName = "MyStructuredTable"; + table.TableStyleType = TableStyleType.TableStyleMedium9; // Apply a built‑in style + table.ShowTotals = true; // Enable totals row + table.ListColumns[0].TotalsCalculation = TotalsCalculation.Sum; // Example total + + // Save the workbook with the new table + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-chart-that-uses-a-worksheet-table-as-its-data-source-and-apply-a-predefined-chart-style.cs b/working-with-tables/create-a-chart-that-uses-a-worksheet-table-as-its-data-source-and-apply-a-predefined-chart-style.cs new file mode 100644 index 0000000000..643762e04b --- /dev/null +++ b/working-with-tables/create-a-chart-that-uses-a-worksheet-table-as-its-data-source-and-apply-a-predefined-chart-style.cs @@ -0,0 +1,46 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +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 (including headers) + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Series1"); + sheet.Cells["C1"].PutValue("Series2"); + + for (int i = 2; i <= 6; i++) + { + sheet.Cells[$"A{i}"].PutValue("Item " + (i - 1)); + sheet.Cells[$"B{i}"].PutValue(i * 10); // Series1 values + sheet.Cells[$"C{i}"].PutValue(i * 15); // Series2 values + } + + // Add a worksheet table (ListObject) that covers the data range. + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = sheet.ListObjects.Add(0, 0, 6, 3, true); + var table = sheet.ListObjects[tableIndex]; + table.DisplayName = "DataTable"; // Table name that can be used in formulas + + // Add a column chart to the worksheet + int chartIndex = sheet.Charts.Add(ChartType.Column, 8, 0, 25, 10); + Chart chart = sheet.Charts[chartIndex]; + + // Set the chart data source to the table columns + // Category (X‑axis) comes from the "Category" column, series from the other columns + chart.NSeries.Add("DataTable[Series1]", true); + chart.NSeries.CategoryData = "DataTable[Category]"; + + // Apply a predefined built‑in chart style (valid values: 1‑48) + chart.Style = 5; // Example style index + + // Save the workbook + workbook.Save("ChartWithTableStyle.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-data-validation-list-that-pulls-its-items-directly-from-a-column-in-a-worksheet-table.cs b/working-with-tables/create-a-data-validation-list-that-pulls-its-items-directly-from-a-column-in-a-worksheet-table.cs new file mode 100644 index 0000000000..40ad6315ed --- /dev/null +++ b/working-with-tables/create-a-data-validation-list-that-pulls-its-items-directly-from-a-column-in-a-worksheet-table.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class ValidationFromTableColumn + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the table (column A) + worksheet.Cells["A1"].PutValue("Item"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["A5"].PutValue("Date"); + + // Add a ListObject (Excel table) that covers the data range A1:A5 + int tableIndex = worksheet.ListObjects.Add("A1", "A5", true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "FruitTable"; + + // Define the cell where the validation will be applied (e.g., B1) + CellArea validationArea = new CellArea + { + StartRow = 0, // Row 1 (zero‑based) + StartColumn = 1, // Column B (zero‑based) + EndRow = 0, + EndColumn = 1 + }; + + // Add a validation to the worksheet for the specified cell area + int validationIdx = worksheet.Validations.Add(validationArea); + Validation validation = worksheet.Validations[validationIdx]; + + // Configure the validation as a List type using a structured reference to the table column + validation.Type = ValidationType.List; + validation.Formula1 = $"{table.DisplayName}[Item]"; + validation.InCellDropDown = true; + + // Save the workbook + string outputPath = "ValidationFromTableColumn.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to: {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + ValidationFromTableColumn.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-duplicate-of-an-existing-table-on-another-worksheet-while-preserving-its-style-and-formulas.cs b/working-with-tables/create-a-duplicate-of-an-existing-table-on-another-worksheet-while-preserving-its-style-and-formulas.cs new file mode 100644 index 0000000000..91efe099d3 --- /dev/null +++ b/working-with-tables/create-a-duplicate-of-an-existing-table-on-another-worksheet-while-preserving-its-style-and-formulas.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using Aspose.Cells; +using AsposeRange = Aspose.Cells.Range; + +namespace AsposeCellsTableDuplicate +{ + class Program + { + static void Main() + { + try + { + const string sourcePath = "source.xlsx"; + const string outputPath = "output.xlsx"; + + // Verify source file exists to avoid FileNotFoundException + if (!File.Exists(sourcePath)) + { + Console.WriteLine($"Source file not found: {sourcePath}"); + return; + } + + // Load the source workbook + Workbook workbook = new Workbook(sourcePath); + + // Assume the table to duplicate is on the first worksheet + Worksheet sourceSheet = workbook.Worksheets[0]; + + // Add a new worksheet for the duplicated table + int newSheetIndex = workbook.Worksheets.Add(); + Worksheet destinationSheet = workbook.Worksheets[newSheetIndex]; + destinationSheet.Name = "DuplicatedTable"; + + // Define the range that contains the original table. + // Adjust the address to match the actual table range in your file. + AsposeRange sourceRange = sourceSheet.Cells.CreateRange("A1:C5"); + + // Define the destination range where the table will be copied. + AsposeRange destinationRange = destinationSheet.Cells.CreateRange("A1:C5"); + + // Set paste options to copy everything (values, formulas, formats, styles, etc.) + PasteOptions pasteOptions = new PasteOptions + { + PasteType = PasteType.All + }; + + // Perform the copy operation preserving formulas and styles. + destinationRange.Copy(sourceRange, pasteOptions); + + // Save the workbook with the duplicated table. + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to {outputPath}"); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-list-object-from-a-dynamic-range-and-enable-automatic-expansion-when-new-rows-are-added.cs b/working-with-tables/create-a-list-object-from-a-dynamic-range-and-enable-automatic-expansion-when-new-rows-are-added.cs new file mode 100644 index 0000000000..a21b4a4371 --- /dev/null +++ b/working-with-tables/create-a-list-object-from-a-dynamic-range-and-enable-automatic-expansion-when-new-rows-are-added.cs @@ -0,0 +1,56 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsListObjectDemo +{ + 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 (including headers) in a dynamic range + // A1:C4 will be the initial range; later rows can be added below it + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Score"); + + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["C2"].PutValue(85); + + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["C3"].PutValue(90); + + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Charlie"); + sheet.Cells["C4"].PutValue(78); + + // Add a ListObject (Excel table) using the range that contains the data + // The range is defined by its start and end cell addresses + ListObjectCollection listObjects = sheet.ListObjects; + int tableIndex = listObjects.Add("A1", "C4", true); // hasHeaders = true + ListObject table = listObjects[tableIndex]; + + // Optional: set a table style for better visual appearance + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Demonstrate automatic expansion: + // Adding a new row directly below the current table expands it automatically + // Use PutCellValue on the row index that is one past the current EndRow + int newRow = table.EndRow + 1; // row index where the new data will be placed + table.PutCellValue(newRow, 0, 4); // ID + table.PutCellValue(newRow, 1, "Diana"); // Name + table.PutCellValue(newRow, 2, 92); // Score + + // At this point the ListObject has automatically grown to include the new row + + // Save the workbook (lifecycle rule compliance) + workbook.Save("DynamicListObject.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-macroenabled-workbook-add-a-table-and-assign-a-vba-macro-to-run-when-the-table-changes.cs b/working-with-tables/create-a-macroenabled-workbook-add-a-table-and-assign-a-vba-macro-to-run-when-the-table-changes.cs new file mode 100644 index 0000000000..2ce7ee187a --- /dev/null +++ b/working-with-tables/create-a-macroenabled-workbook-add-a-table-and-assign-a-vba-macro-to-run-when-the-table-changes.cs @@ -0,0 +1,105 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Vba; + +namespace AsposeCellsMacroTableDemo +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook (lifecycle rule: create) + Workbook wb = new Workbook(); + + // Enable macros for the workbook (required for macro‑enabled files) + wb.Settings.EnableMacros = true; + + // Access the first worksheet + Worksheet sheet = wb.Worksheets[0]; + sheet.Name = "DataSheet"; + + // Populate sample data (A1:C5) + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Amount"); + + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["C2"].PutValue(100); + + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["C3"].PutValue(200); + + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Charlie"); + sheet.Cells["C4"].PutValue(300); + + sheet.Cells["A5"].PutValue(4); + sheet.Cells["B5"].PutValue("Diana"); + sheet.Cells["C5"].PutValue(400); + + // Add a table (ListObject) covering the data range A1:C5 + int firstRow = 0; // zero‑based index for row 1 + int firstColumn = 0; // zero‑based index for column A + int totalRows = 5; // rows 1‑5 + int totalColumns = 3; // columns A‑C + + // Add the ListObject and then set its display name + sheet.ListObjects.Add(firstRow, firstColumn, totalRows, totalColumns, true); + var table = sheet.ListObjects[sheet.ListObjects.Count - 1]; + table.DisplayName = "MyTable"; // use DisplayName instead of Name + + // ------------------------------------------------------------ + // Add VBA code that runs when the table changes. + // The code is placed in the worksheet's code module (document module). + // ------------------------------------------------------------ + + // Create a VBA module associated with the worksheet + int moduleIndex = wb.VbaProject.Modules.Add(sheet); + VbaModule sheetModule = wb.VbaProject.Modules[moduleIndex]; + + // VBA source code + string vbaCode = @" +Private Sub Worksheet_Change(ByVal Target As Range) + On Error GoTo ExitHandler + Dim tbl As ListObject + Set tbl = Me.ListObjects(""MyTable"") + If Not Intersect(Target, tbl.Range) Is Nothing Then + Call TableChanged + End If +ExitHandler: +End Sub + +Sub TableChanged() + MsgBox ""The table 'MyTable' has been modified."" +End Sub +"; + + // Assign the VBA code to the module + sheetModule.Codes = vbaCode; + + // Save the workbook as a macro‑enabled file (lifecycle rule: save) + string outputPath = "MacroEnabledTable.xlsm"; + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + wb.Save(outputPath, SaveFormat.Xlsm); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + // Log or display the error + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-new-worksheet-table-from-a-range-of-cells-and-assign-a-custom-name.cs b/working-with-tables/create-a-new-worksheet-table-from-a-range-of-cells-and-assign-a-custom-name.cs new file mode 100644 index 0000000000..875b072b72 --- /dev/null +++ b/working-with-tables/create-a-new-worksheet-table-from-a-range-of-cells-and-assign-a-custom-name.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Needed for ListObject +using AsposeRange = Aspose.Cells.Range; + +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 in the range A1:C4 + for (int row = 0; row < 4; row++) + { + for (int col = 0; col < 3; col++) + { + cells[row, col].PutValue($"R{row + 1}C{col + 1}"); + } + } + + // Create a Range object that covers the data (alias to avoid conflict with System.Range) + AsposeRange dataRange = cells.CreateRange("A1", "C4"); + + // Add a ListObject (table) based on the range + int tableIndex = sheet.ListObjects.Add( + dataRange.FirstRow, + dataRange.FirstColumn, + dataRange.FirstRow + dataRange.RowCount - 1, + dataRange.FirstColumn + dataRange.ColumnCount - 1, + true); // true indicates the range has a header row + + // Retrieve the created table + ListObject table = sheet.ListObjects[tableIndex]; + + // Assign a custom name to the table + table.DisplayName = "CustomTable"; + + // Save the workbook + string outputPath = "TableWithCustomName.xlsx"; + 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/working-with-tables/create-a-table-from-an-external-csv-file-using-a-query-table-data-source-and-map-columns-automatically.cs b/working-with-tables/create-a-table-from-an-external-csv-file-using-a-query-table-data-source-and-map-columns-automatically.cs new file mode 100644 index 0000000000..efdc883505 --- /dev/null +++ b/working-with-tables/create-a-table-from-an-external-csv-file-using-a-query-table-data-source-and-map-columns-automatically.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + try + { + // Verify that the CSV file exists to avoid FileNotFoundException + string csvFilePath = "data.csv"; + if (!File.Exists(csvFilePath)) + { + Console.WriteLine($"CSV file not found: {csvFilePath}"); + return; + } + + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Import CSV data starting at cell A1 (comma delimiter, auto‑detect numeric values) + cells.ImportCSV(csvFilePath, ",", true, 0, 0); + + // Determine the used range after import + int lastRow = cells.MaxDataRow; + int lastColumn = cells.MaxDataColumn; + + // Add a ListObject (Excel table) that covers the imported data + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int listObjectIndex = worksheet.ListObjects.Add(0, 0, lastRow + 1, lastColumn + 1, true); + ListObject listObject = worksheet.ListObjects[listObjectIndex]; + + // Set a friendly name for the table + listObject.DisplayName = "CsvQueryTable"; + + // Auto‑fit columns for better readability + worksheet.AutoFitColumns(); + + // Save the workbook + workbook.Save("output.xlsx", SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-a-sharepoint-document-for-reference.cs b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-a-sharepoint-document-for-reference.cs new file mode 100644 index 0000000000..f0ac712cfc --- /dev/null +++ b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-a-sharepoint-document-for-reference.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +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 that will become the table + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // Add a ListObject (Excel table) covering the data range A1:B3 + int tableIdx = sheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = sheet.ListObjects[tableIdx]; + table.DisplayName = "Employees"; + + // Attach a comment to the table that contains a SharePoint hyperlink (as plain text) + table.Comment = "Reference document: https://sharepoint.company.com/sites/docs/EmployeeGuide.docx"; + + // Add a clickable hyperlink to the first cell of the table (A1) pointing to the same SharePoint document + int hyperlinkIdx = sheet.Hyperlinks.Add("A1", 1, 1, "https://sharepoint.company.com/sites/docs/EmployeeGuide.docx"); + Hyperlink hyperlink = sheet.Hyperlinks[hyperlinkIdx]; + hyperlink.TextToDisplay = "Employee Guide"; + hyperlink.ScreenTip = "Open SharePoint document"; + + // Save the workbook + workbook.Save("TableWithCommentAndHyperlink.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-external-documentation-for-reference.cs b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-external-documentation-for-reference.cs new file mode 100644 index 0000000000..8f6b1fbf08 --- /dev/null +++ b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-a-hyperlink-to-external-documentation-for-reference.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +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 that will become the table + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // Add a ListObject (Excel table) covering the range A1:B3, with a header row + int tableIdx = sheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = sheet.ListObjects[tableIdx]; + + // Set a display name for the table (Name property may not be available in some versions) + table.DisplayName = "SampleTable"; + + // Attach a comment to the table that contains a hyperlink to external documentation + string docUrl = "https://docs.aspose.com/cells/net/working-with-tables/"; + table.Comment = $"For more details see Aspose.Cells Table Documentation"; + + // Define output file path + string outputPath = "TableWithComment.xlsx"; + + // Save the workbook + workbook.Save(outputPath, SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-attach-a-comment-that-includes-the-creation-timestamp-and-author-information-for-audit.cs b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-the-creation-timestamp-and-author-information-for-audit.cs new file mode 100644 index 0000000000..7e1d65ba06 --- /dev/null +++ b/working-with-tables/create-a-table-then-attach-a-comment-that-includes-the-creation-timestamp-and-author-information-for-audit.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableCommentDemo +{ + 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]; + + // Sample data for the table (header + two rows) + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + + // Define author information + string author = "John Doe"; + + // Create a ListObject (table) that covers the data range + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Attach an audit comment to the table with timestamp and author + table.Comment = $"Created by {author} on {DateTime.Now:yyyy-MM-dd HH:mm:ss}"; + + // Save the workbook + workbook.Save("TableWithAuditComment.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-generate-a-chart-that-uses-the-tables-totals-row-as-the-data-series-source.cs b/working-with-tables/create-a-table-then-generate-a-chart-that-uses-the-tables-totals-row-as-the-data-series-source.cs new file mode 100644 index 0000000000..9d2899323a --- /dev/null +++ b/working-with-tables/create-a-table-then-generate-a-chart-that-uses-the-tables-totals-row-as-the-data-series-source.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using Aspose.Cells.Charts; + +class TableTotalsChartExample +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate header and sample data (3 data rows) + 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("C"); + sheet.Cells["B4"].PutValue(30); + + // Create a table (ListObject) that includes the header and data rows (A1:B4) + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = sheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "MyTable"; // Optional: give the table a name + table.ShowTotals = true; // Enable the totals row + + // Set the totals calculation for the "Value" column (second column, index 1) + table.ListColumns[1].TotalsCalculation = TotalsCalculation.Sum; + + // Determine the address of the totals row cells for the two columns + // Totals row is placed immediately after the data rows. + int totalsRowIndex = table.StartRow + table.DataRange.RowCount; // zero‑based index + + // Column letters for the two columns + string valueColumnLetter = CellsHelper.ColumnIndexToName(table.StartColumn + 1); // "B" + string categoryColumnLetter = CellsHelper.ColumnIndexToName(table.StartColumn); // "A" + + // Build the A1‑style references for the totals row cells + string valueCellRef = $"=Sheet1!${valueColumnLetter}${totalsRowIndex + 1}"; + string categoryCellRef = $"=Sheet1!${categoryColumnLetter}${totalsRowIndex + 1}"; + + // Add a column chart to the worksheet + int chartIndex = sheet.Charts.Add(ChartType.Column, 6, 0, 25, 10); + Chart chart = sheet.Charts[chartIndex]; + + // Use the totals row as the data source for the series + chart.NSeries.Add(valueCellRef, true); // Series values from totals row + chart.NSeries[0].Name = "Total"; // Optional series name + chart.NSeries.CategoryData = categoryCellRef; // Category label from totals row + + // Optional: set a chart title + chart.Title.Text = "Totals Row Chart"; + + // Save the workbook + string outputPath = "TableTotalsChart.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/working-with-tables/create-a-table-then-generate-a-data-validation-rule-restricting-entries-to-values-present-in-another-table-column.cs b/working-with-tables/create-a-table-then-generate-a-data-validation-rule-restricting-entries-to-values-present-in-another-table-column.cs new file mode 100644 index 0000000000..7b1ded7759 --- /dev/null +++ b/working-with-tables/create-a-table-then-generate-a-data-validation-rule-restricting-entries-to-values-present-in-another-table-column.cs @@ -0,0 +1,54 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +class Program +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // ---------- Create source table ---------- + // Header in A1 + worksheet.Cells["A1"].PutValue("Item"); + // Sample items in A2:A5 + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["A5"].PutValue("Date"); + + // Add a ListObject (Excel table) that covers A1:A5 + int tableIdx = worksheet.ListObjects.Add("A1", "A5", true); + ListObject table = worksheet.ListObjects[tableIdx]; + table.DisplayName = "ItemsTable"; // Optional friendly name + + // ---------- Create data validation ---------- + // Validation will be placed in cell B1 + Validation validation = worksheet.Cells["B1"].GetValidation(); + + // Restrict entries to a list type + validation.Type = ValidationType.List; + + // Use a structured reference to the column of the table as the source list + validation.Formula1 = "=ItemsTable[Item]"; + + // Show a drop‑down arrow in the cell + validation.InCellDropDown = true; + + // Explicitly apply the validation to B1 (optional) + CellArea area = CellArea.CreateCellArea(0, 1, 0, 1); // Row 0, Column 1 => B1 + validation.AddArea(area); + + // ---------- Save the workbook ---------- + workbook.Save("TableValidationDemo.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-data-body-range-excluding-headers.cs b/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-data-body-range-excluding-headers.cs new file mode 100644 index 0000000000..b9bf84240c --- /dev/null +++ b/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-data-body-range-excluding-headers.cs @@ -0,0 +1,51 @@ +using System; +using System.Text; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; +using ARange = Aspose.Cells.Range; + +class Program +{ + static void Main() + { + try + { + // Register encoding provider (required for .NET Core) + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data with headers + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Bob"); + + // Add a ListObject (table) covering the range A1:B4, indicating that the range has headers + int tableIndex = sheet.ListObjects.Add("A1", "B4", true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "EmployeeTable"; + + // Retrieve the data range of the table (excludes header row) + ARange dataRange = table.DataRange; + + // Create a named range that references only the data body of the table + dataRange.Name = "EmployeeData"; + + // Save the workbook + string outputPath = "TableWithNamedDataRange.xlsx"; + workbook.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-header-row-for-use-in-formulas.cs b/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-header-row-for-use-in-formulas.cs new file mode 100644 index 0000000000..8de60905f5 --- /dev/null +++ b/working-with-tables/create-a-table-then-generate-a-named-range-that-references-only-the-header-row-for-use-in-formulas.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsHeaderNamedRangeDemo +{ + class Program + { + 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 header row + cells["A1"].PutValue("Product"); + cells["B1"].PutValue("Price"); + + // Populate some data rows + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(2.5); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(1.8); + + // Define the table range (including header) + int startRow = 0; // Row index for "A1" + int startColumn = 0; // Column index for "A1" + int endRow = 2; // Row index for "B3" + int endColumn = 1; // Column index for "B3" + bool hasHeaders = true; + + // Add the ListObject (table) to the worksheet + int tableIndex = worksheet.ListObjects.Add(startRow, startColumn, endRow, endColumn, hasHeaders); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "ProductTable"; + + // Create a named range that refers only to the header row of the table + // Header row is the first row of the table range (startRow, startColumn) with 1 row and the same column count as the table + int headerRowCount = 1; + int headerColumnCount = table.ListColumns.Count; // Number of columns in the table + Aspose.Cells.Range headerRange = cells.CreateRange(startRow, startColumn, headerRowCount, headerColumnCount); + headerRange.Name = "ProductHeaders"; // Named range for the header row + + // Example usage of the named range in a formula (count number of header cells) + cells["C1"].Formula = "=COUNTA(ProductHeaders)"; + workbook.CalculateFormula(); + Console.WriteLine("Header count (should be 2): " + cells["C1"].IntValue); + + // Save the workbook (ensure the directory exists) + string outputPath = "HeaderNamedRangeDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (FileNotFoundException fnfEx) + { + Console.WriteLine($"File not found: {fnfEx.FileName}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-then-generate-a-pivot-chart-from-its-data-and-place-it-on-a-dashboard-sheet.cs b/working-with-tables/create-a-table-then-generate-a-pivot-chart-from-its-data-and-place-it-on-a-dashboard-sheet.cs new file mode 100644 index 0000000000..5162248c82 --- /dev/null +++ b/working-with-tables/create-a-table-then-generate-a-pivot-chart-from-its-data-and-place-it-on-a-dashboard-sheet.cs @@ -0,0 +1,71 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Charts; + +class PivotChartDashboard +{ + static void Main() + { + // 1. Create a new workbook + Workbook workbook = new Workbook(); + + // 2. Add sample data to the first worksheet (acts as a table) + Worksheet dataSheet = workbook.Worksheets[0]; + dataSheet.Name = "Data"; + + // Header + 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("Travel"); + dataSheet.Cells["B3"].PutValue(80); + dataSheet.Cells["A4"].PutValue("Food"); + dataSheet.Cells["B4"].PutValue(150); + dataSheet.Cells["A5"].PutValue("Utilities"); + dataSheet.Cells["B5"].PutValue(200); + + // 3. Add a worksheet that will hold the PivotTable + Worksheet pivotSheet = workbook.Worksheets.Add("Pivot"); + + // 4. Define the source data range for the pivot table + // Use the MaxDisplayRange to get the used range dynamically + string sourceRange = $"=Data!{dataSheet.Cells.MaxDisplayRange.Address}"; + + // 5. Add a PivotTable (using the Add(string, string, string) rule) + int pivotIndex = pivotSheet.PivotTables.Add(sourceRange, "A1", "SalesPivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIndex]; + + // 6. Configure the PivotTable fields + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); // Row field + pivotTable.AddFieldToArea(PivotFieldType.Data, "Amount"); // Data field (sum) + + // Optional: display in tabular form + pivotTable.ShowInTabularForm(); + + // Refresh and calculate the pivot data + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // 7. Add a dashboard worksheet where the pivot chart will be placed + Worksheet dashboardSheet = workbook.Worksheets.Add("Dashboard"); + + // 8. Add a chart to the dashboard sheet (using the Charts.Add rule) + // Parameters: ChartType, first row, first column, last row, last column + int chartIndex = dashboardSheet.Charts.Add(ChartType.Column, 2, 0, 20, 7); + Chart chart = dashboardSheet.Charts[chartIndex]; + + // 9. Link the chart to the pivot table (using Chart.PivotSource property) + // Since the pivot table is on the "Pivot" sheet, reference it accordingly + chart.PivotSource = "Pivot!SalesPivot"; + + // 10. Refresh the chart to pull data from the pivot table (using RefreshPivotData) + chart.RefreshPivotData(); + + // 11. Save the workbook + workbook.Save("PivotChartDashboard.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-with-a-calculated-column-that-concatenates-first-and-last-name-fields-for-each-row.cs b/working-with-tables/create-a-table-with-a-calculated-column-that-concatenates-first-and-last-name-fields-for-each-row.cs new file mode 100644 index 0000000000..77a6612927 --- /dev/null +++ b/working-with-tables/create-a-table-with-a-calculated-column-that-concatenates-first-and-last-name-fields-for-each-row.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class TableWithCalculatedColumn +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data with headers + sheet.Cells["A1"].PutValue("FirstName"); + sheet.Cells["B1"].PutValue("LastName"); + sheet.Cells["C1"].PutValue("FullName"); // Header for the calculated column + + // Sample rows + sheet.Cells["A2"].PutValue("John"); + sheet.Cells["B2"].PutValue("Doe"); + + sheet.Cells["A3"].PutValue("Jane"); + sheet.Cells["B3"].PutValue("Smith"); + + sheet.Cells["A4"].PutValue("Bob"); + sheet.Cells["B4"].PutValue("Johnson"); + + // Define the range that will become a table (including header row) + // Rows: 0‑4 (5 rows, 0‑based), Columns: 0‑2 (3 columns) + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "People"; + table.ShowHeaderRow = true; + + // Set the formula for the calculated column using structured references + // This formula will be applied to each row of the table + table.ListColumns[2].Formula = "=[@FirstName] & \" \" & [@LastName]"; + + // Optionally, show totals row (not required for this task) + table.ShowTotals = false; + + // Save the workbook + workbook.Save("TableWithCalculatedColumn.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-with-a-calculated-column-using-the-today-function-to-display-days-since-a-start-date.cs b/working-with-tables/create-a-table-with-a-calculated-column-using-the-today-function-to-display-days-since-a-start-date.cs new file mode 100644 index 0000000000..6b74c55d07 --- /dev/null +++ b/working-with-tables/create-a-table-with-a-calculated-column-using-the-today-function-to-display-days-since-a-start-date.cs @@ -0,0 +1,63 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class TableWithCalculatedColumnDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Define headers for the table + cells["A1"].PutValue("StartDate"); // Column with the start date + cells["B1"].PutValue("DaysSinceStart"); // Calculated column + + // Populate some start dates (example dates) + cells["A2"].PutValue(new DateTime(2023, 1, 1)); + cells["A3"].PutValue(new DateTime(2023, 2, 15)); + cells["A4"].PutValue(new DateTime(2023, 3, 10)); + cells["A5"].PutValue(new DateTime(2023, 4, 20)); + + // Create a ListObject (Excel table) that includes the data range A1:B5 + // The last parameter 'true' indicates that the first row contains headers + int tableIndex = sheet.ListObjects.Add("A1", "B5", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Set the formula for the calculated column using a structured reference. + // The formula calculates the number of days between TODAY() and the start date in the same row. + // Row offset starts at 1 for the first data row (row 2 in the worksheet). + for (int rowOffset = 1; rowOffset <= 4; rowOffset++) + { + // Column offset 1 corresponds to the second column ("DaysSinceStart") + table.PutCellFormula(rowOffset, 1, "=TODAY()-[@StartDate]"); + } + + // Recalculate all formulas so that the new column shows the correct values + workbook.CalculateFormula(); + + // Save the workbook + workbook.Save("TableWithCalculatedColumn.xlsx"); + Console.WriteLine("Workbook saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + TableWithCalculatedColumnDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/create-a-table-with-a-dynamic-named-range-that-expands-automatically-when-new-rows-are-added.cs b/working-with-tables/create-a-table-with-a-dynamic-named-range-that-expands-automatically-when-new-rows-are-added.cs new file mode 100644 index 0000000000..955ca9df4f --- /dev/null +++ b/working-with-tables/create-a-table-with-a-dynamic-named-range-that-expands-automatically-when-new-rows-are-added.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class DynamicTableWithNamedRange +{ + 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 with headers + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["A3"].PutValue(2); + cells["B3"].PutValue("Bob"); + + // Create a ListObject (table) that covers the data range A1:B3 + int tableIndex = sheet.ListObjects.Add("A1", "B3", true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "MyTable"; // friendly name for the table + + // Define a dynamic named range that refers to the whole table. + // The structured reference "MyTable[#All]" expands automatically as rows are added. + int nameIndex = workbook.Worksheets.Names.Add("MyDynamicRange"); + Name dynamicName = workbook.Worksheets.Names[nameIndex]; + dynamicName.RefersTo = $"={sheet.Name}!{table.DisplayName}[#All]"; + + // Determine the next row index after the current table data + int lastDataRow = table.DataRange.FirstRow + table.DataRange.RowCount - 1; + int newRow = lastDataRow + 1; + + // Write new data (the table expands automatically when saved) + cells[newRow, 0].PutValue(3); // ID column + cells[newRow, 1].PutValue("Charlie"); // Name column + + // Save the workbook + string outputPath = "DynamicTableNamedRange.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/working-with-tables/create-a-table-with-a-header-row-that-uses-merged-cells-to-span-multiple-columns-for-a-title.cs b/working-with-tables/create-a-table-with-a-header-row-that-uses-merged-cells-to-span-multiple-columns-for-a-title.cs new file mode 100644 index 0000000000..201c617ade --- /dev/null +++ b/working-with-tables/create-a-table-with-a-header-row-that-uses-merged-cells-to-span-multiple-columns-for-a-title.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class MergedHeaderTableDemo + { + public static void Main() + { + try + { + Run(); + Console.WriteLine("Workbook created successfully."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // 1. Create a title that spans across 4 columns (A1:D1) + cells.Merge(0, 0, 1, 4); + cells[0, 0].PutValue("Sales Report 2024"); + Style titleStyle = cells[0, 0].GetStyle(); + titleStyle.HorizontalAlignment = TextAlignmentType.Center; + titleStyle.Font.IsBold = true; + titleStyle.Font.Size = 14; + cells[0, 0].SetStyle(titleStyle); + + // 2. Add column headers (row 2) + string[] headers = { "Region", "Product", "Quantity", "Revenue" }; + for (int col = 0; col < headers.Length; col++) + { + cells[1, col].PutValue(headers[col]); + Style headerStyle = cells[1, col].GetStyle(); + headerStyle.Font.IsBold = true; + headerStyle.HorizontalAlignment = TextAlignmentType.Center; + cells[1, col].SetStyle(headerStyle); + } + + // 3. Add sample data starting from row 3 + object[,] data = { + { "North", "Apples", 120, 2400 }, + { "South", "Oranges", 85, 1700 }, + { "East", "Bananas", 150, 3000 }, + { "West", "Grapes", 60, 1800 } + }; + + for (int row = 0; row < data.GetLength(0); row++) + { + for (int col = 0; col < data.GetLength(1); col++) + { + cells[2 + row, col].PutValue(data[row, col]); + } + } + + // 4. Auto‑fit columns to display content nicely + worksheet.AutoFitColumns(); + + // Save the workbook to a file + string outputPath = "MergedHeaderTable.xlsx"; + try + { + workbook.Save(outputPath); + } + catch (Exception saveEx) + { + Console.Error.WriteLine($"Failed to save workbook: {saveEx.Message}"); + throw; + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/define-tabletorangeoptionslastrow-dynamically-based-on-listobjectrowscount-before-converting-the-table-to-a-range.cs b/working-with-tables/define-tabletorangeoptionslastrow-dynamically-based-on-listobjectrowscount-before-converting-the-table-to-a-range.cs new file mode 100644 index 0000000000..1fa68104ce --- /dev/null +++ b/working-with-tables/define-tabletorangeoptionslastrow-dynamically-based-on-listobjectrowscount-before-converting-the-table-to-a-range.cs @@ -0,0 +1,48 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsDynamicLastRowDemo +{ + 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]; + Cells cells = worksheet.Cells; + + // Populate sample data (5 columns, 10 rows) + for (int row = 0; row < 10; row++) + { + for (int col = 0; col < 5; col++) + { + cells[row, col].PutValue($"R{row}C{col}"); + } + } + + // Add a ListObject (table) that covers the populated range + // Parameters: startRow, startColumn, endRow, endColumn, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 9, 4, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Dynamically determine the last row index of the table. + // EndRow returns the zero‑based index of the last row of the table (including header if present). + // This value reflects the current number of rows in the table. + int dynamicLastRow = table.EndRow; + + // Create conversion options and set LastRow to the dynamically obtained value + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = dynamicLastRow + }; + + // Convert the table to a range using the options + table.ConvertToRange(options); + + // Save the workbook + workbook.Save("TableToRange_DynamicLastRow.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/delete-a-specific-row-from-a-table-using-its-primary-key-value-to-locate-the-target.cs b/working-with-tables/delete-a-specific-row-from-a-table-using-its-primary-key-value-to-locate-the-target.cs new file mode 100644 index 0000000000..310c603bc6 --- /dev/null +++ b/working-with-tables/delete-a-specific-row-from-a-table-using-its-primary-key-value-to-locate-the-target.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsExamples +{ + public class DeleteRowByPrimaryKey + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Add a header row (ID as primary key, Name as data) + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + + // Populate sample data + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["A3"].PutValue(2); + cells["B3"].PutValue("Bob"); + cells["A4"].PutValue(3); + cells["B4"].PutValue("Charlie"); + + // Create a table (ListObject) that uses the data range + int firstRow = 0; // zero‑based index for header + int firstColumn = 0; + int totalRows = 4; // header + 3 data rows + int totalColumns = 2; + + int tableIndex = sheet.ListObjects.Add( + firstRow, + firstColumn, + firstRow + totalRows - 1, + firstColumn + totalColumns - 1, + true); + + ListObject table = sheet.ListObjects[tableIndex]; + table.ShowHeaderRow = true; + + // Primary key value to delete + int targetId = 2; + + // Locate the row index (zero‑based) that contains the target primary key + int rowToDelete = -1; + for (int row = 1; row <= sheet.Cells.MaxDataRow; row++) // start after header + { + // Ensure the cell contains a numeric value before comparing + if (cells[row, 0].Type == CellValueType.IsNumeric && + cells[row, 0].IntValue == targetId) + { + rowToDelete = row; + break; + } + } + + if (rowToDelete != -1) + { + // Delete the identified row and shift cells up + cells.DeleteRow(rowToDelete, true); + Console.WriteLine($"Row with ID {targetId} deleted (zero‑based index {rowToDelete})."); + } + else + { + Console.WriteLine($"Row with ID {targetId} not found."); + } + + // Save the workbook to verify the result + string outputPath = "DeleteRowByPrimaryKey.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point required for console application + public class Program + { + public static void Main(string[] args) + { + DeleteRowByPrimaryKey.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/delete-all-rows-from-a-table-that-have-a-null-value-in-a-required-column-using-a-loop.cs b/working-with-tables/delete-all-rows-from-a-table-that-have-a-null-value-in-a-required-column-using-a-loop.cs new file mode 100644 index 0000000000..e800e2e0be --- /dev/null +++ b/working-with-tables/delete-all-rows-from-a-table-that-have-a-null-value-in-a-required-column-using-a-loop.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using Aspose.Cells; + +class DeleteRowsWithNullInRequiredColumn +{ + 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)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Index of the required column (0 = column A) + int requiredColumnIndex = 0; + + // Iterate from the last data row up to the first row + // Deleting from bottom prevents index shifting issues + for (int row = cells.MaxDataRow; row >= 0; row--) + { + Cell cell = cells[row, requiredColumnIndex]; + + // Determine if the cell is considered "null" (blank, DBNull, or empty string) + bool isNull = cell.Value == null || + (cell.Type == CellValueType.IsString && string.IsNullOrWhiteSpace(cell.StringValue)); + + if (isNull) + { + // Delete the entire row + cells.DeleteRow(row); + } + } + + // Save the modified workbook + workbook.Save(outputPath, SaveFormat.Xlsx); + Console.WriteLine($"Workbook saved successfully to {outputPath}"); + } + catch (Exception ex) + { + // Log or display the exception details for troubleshooting + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/delete-the-comment-attached-to-the-table-to-clean-up-metadata-after-final-review.cs b/working-with-tables/delete-the-comment-attached-to-the-table-to-clean-up-metadata-after-final-review.cs new file mode 100644 index 0000000000..d780f65d8a --- /dev/null +++ b/working-with-tables/delete-the-comment-attached-to-the-table-to-clean-up-metadata-after-final-review.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace DeleteTableCommentApp +{ + class DeleteTableComment + { + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Ensure the input file exists before loading + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Iterate through worksheets and their tables (ListObjects) + foreach (Worksheet worksheet in workbook.Worksheets) + { + foreach (ListObject table in worksheet.ListObjects) + { + // Remove any comment attached to the table + table.Comment = string.Empty; + } + } + + // Save the modified workbook + workbook.Save(outputPath, SaveFormat.Xlsx); + 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/working-with-tables/disable-autoexpand-for-a-table-to-keep-its-range-fixed-despite-additional-rows-being-entered.cs b/working-with-tables/disable-autoexpand-for-a-table-to-keep-its-range-fixed-despite-additional-rows-being-entered.cs new file mode 100644 index 0000000000..b3e758d37b --- /dev/null +++ b/working-with-tables/disable-autoexpand-for-a-table-to-keep-its-range-fixed-despite-additional-rows-being-entered.cs @@ -0,0 +1,63 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class DisableTableAutoExpandDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate some initial data (including header row) + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + for (int i = 2; i <= 5; i++) + { + sheet.Cells[i - 1, 0].PutValue(i - 1); // ID column + sheet.Cells[i - 1, 1].PutValue($"Item {i - 1}"); // Name column + } + + // Add a ListObject (table) covering the data range A1:B5 + int tableIndex = sheet.ListObjects.Add("A1", "B5", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Auto‑expand is not required for this demo; the table range will stay fixed + // (If the API supported it, you could set table.AutoExpand = false;) + + // Add additional rows *outside* the original table range + // These rows will not be included in the table because we do not expand it + sheet.Cells["A6"].PutValue(6); + sheet.Cells["B6"].PutValue("Item 6"); + sheet.Cells["A7"].PutValue(7); + sheet.Cells["B7"].PutValue("Item 7"); + + // Verify that the table range has not changed + Console.WriteLine($"Table range after adding rows: {table.StartRow}-{table.EndRow}, {table.StartColumn}-{table.EndColumn}"); + // Expected output: 0-4 (rows 0‑4 correspond to A1:B5) + + // Save the workbook + workbook.Save("TableAutoExpandDisabled.xlsx"); + Console.WriteLine("Workbook saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + DisableTableAutoExpandDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/disable-the-ability-for-users-to-add-new-rows-to-the-list-object-to-enforce-fixed-dataset-size.cs b/working-with-tables/disable-the-ability-for-users-to-add-new-rows-to-the-list-object-to-enforce-fixed-dataset-size.cs new file mode 100644 index 0000000000..892745847b --- /dev/null +++ b/working-with-tables/disable-the-ability-for-users-to-add-new-rows-to-the-list-object-to-enforce-fixed-dataset-size.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsDemo +{ + class DisableAddRowsDemo + { + public static void Run() + { + try + { + // 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("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + + // Add a ListObject (table) covering the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Access protection settings + Protection protection = worksheet.Protection; + + // Disallow inserting rows while the sheet is protected + protection.AllowInsertingRow = false; + + // Set a password and protect the worksheet + protection.Password = "pwd123"; + worksheet.Protect(ProtectionType.All); + + // Define output file path + string outputPath = "FixedTable.xlsx"; + + // Save the workbook + workbook.Save(outputPath, SaveFormat.Xlsx); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + class Program + { + static void Main(string[] args) + { + DisableAddRowsDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/enable-autofilter-on-the-table-and-define-a-filter-to-show-only-rows-with-values-above-threshold.cs b/working-with-tables/enable-autofilter-on-the-table-and-define-a-filter-to-show-only-rows-with-values-above-threshold.cs new file mode 100644 index 0000000000..c2f2a4d135 --- /dev/null +++ b/working-with-tables/enable-autofilter-on-the-table-and-define-a-filter-to-show-only-rows-with-values-above-threshold.cs @@ -0,0 +1,40 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +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 (header + 4 rows) + worksheet.Cells["A1"].PutValue("Item"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(50); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(30); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(70); + worksheet.Cells["A5"].PutValue("Date"); + worksheet.Cells["B5"].PutValue(20); + + // Create a ListObject (table) that covers the data range A1:B5 + int tableIndex = worksheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject listObject = worksheet.ListObjects[tableIndex]; + + // Enable auto‑filter for the table + listObject.HasAutoFilter = true; + + // Define a threshold and filter the "Quantity" column (index 1) to show rows > threshold + int threshold = 40; + listObject.AutoFilter.Custom(1, FilterOperatorType.GreaterThan, threshold); + listObject.AutoFilter.Refresh(); + + // Save the workbook + workbook.Save("FilteredTable.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/enable-the-list-objects-header-row-and-customize-its-background-color-using-a-predefined-style.cs b/working-with-tables/enable-the-list-objects-header-row-and-customize-its-background-color-using-a-predefined-style.cs new file mode 100644 index 0000000000..ef6c4f1586 --- /dev/null +++ b/working-with-tables/enable-the-list-objects-header-row-and-customize-its-background-color-using-a-predefined-style.cs @@ -0,0 +1,76 @@ +using System; +using System.Drawing; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class ListObjectHeaderStyleDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the table (including header) + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Price"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(2.5); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(1.8); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(3.2); + + // Add a ListObject (table) covering the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B4", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Ensure the header row is visible + table.ShowHeaderRow = true; + + // Create a custom style for the header row + Style headerStyle = workbook.CreateStyle(); + headerStyle.Pattern = BackgroundType.Solid; + headerStyle.BackgroundColor = Color.LightGreen; // Desired background color + headerStyle.Font.IsBold = true; // Optional: make header text bold + + // Create a new table style and set the HeaderRow element style + string customStyleName = "MyHeaderStyle"; + TableStyleCollection tableStyles = workbook.Worksheets.TableStyles; + int styleIdx = tableStyles.AddTableStyle(customStyleName); + TableStyle customTableStyle = tableStyles[styleIdx]; + + TableStyleElementCollection elements = customTableStyle.TableStyleElements; + int headerElementIdx = elements.Add(TableStyleElementType.HeaderRow); + TableStyleElement headerElement = elements[headerElementIdx]; + headerElement.SetElementStyle(headerStyle); + + // Apply the custom table style to the list object + table.TableStyleName = customStyleName; + + // Save the workbook + string outputPath = "ListObjectHeaderStyleDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + ListObjectHeaderStyleDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/enable-the-tables-autoexpand-feature-so-that-adding-data-below-expands-the-table-range-automatically.cs b/working-with-tables/enable-the-tables-autoexpand-feature-so-that-adding-data-below-expands-the-table-range-automatically.cs new file mode 100644 index 0000000000..36266ee0da --- /dev/null +++ b/working-with-tables/enable-the-tables-autoexpand-feature-so-that-adding-data-below-expands-the-table-range-automatically.cs @@ -0,0 +1,61 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableAutoExpandDemo +{ + 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]; + Cells cells = worksheet.Cells; + + // ---------- Create initial table ---------- + // Add header row + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + + // Add a few data rows + for (int i = 0; i < 3; i++) + { + cells[i + 1, 0].PutValue(i + 1); // ID + cells[i + 1, 1].PutValue($"Item {i + 1}"); // Name + } + + // Create a ListObject (table) covering the header and the three data rows + // Parameters: startRow, startColumn, endRow, endColumn, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "SampleTable"; + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // ---------- Add new data below the existing table ---------- + // New rows start at row index 4 (zero‑based) because rows 0‑3 are already used + int newRowsStart = 4; + int rowsToAdd = 2; // number of new data rows + + for (int i = 0; i < rowsToAdd; i++) + { + int rowIndex = newRowsStart + i; + cells[rowIndex, 0].PutValue(rowIndex); // ID + cells[rowIndex, 1].PutValue($"NewItem {rowIndex}"); // Name + } + + // ---------- Enable auto‑expand by resizing the table ---------- + // New end row is the last row that now contains data + int newEndRow = newRowsStart + rowsToAdd - 1; + // Resize the table to include the newly added rows + // ListObject.Resize(startRow, startColumn, endRow, endColumn, hasHeaders) + table.Resize(0, 0, newEndRow, 1, true); + + // Optional: Auto‑fit columns for better visibility + worksheet.AutoFitColumns(); + + // Save the workbook + workbook.Save("TableAutoExpandDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/enable-the-tables-autofilter-and-apply-a-custom-filter-showing-rows-where-the-amount-is-between-two-values.cs b/working-with-tables/enable-the-tables-autofilter-and-apply-a-custom-filter-showing-rows-where-the-amount-is-between-two-values.cs new file mode 100644 index 0000000000..c4c19b7443 --- /dev/null +++ b/working-with-tables/enable-the-tables-autofilter-and-apply-a-custom-filter-showing-rows-where-the-amount-is-between-two-values.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class AutoFilterBetweenValuesDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data with a header and some numeric amounts + worksheet.Cells["A1"].PutValue("Amount"); + double[] amounts = { 120.5, 75.0, 200.0, 50.0, 180.0, 90.0 }; + for (int i = 0; i < amounts.Length; i++) + { + // Data starts from row 2 (index 1) + worksheet.Cells[i + 1, 0].PutValue(amounts[i]); + } + + // Define the auto‑filter range covering the header and data in column A + // Parameters: start row (0), start column (0), end column (0) – column A only + worksheet.AutoFilter.SetRange(0, 0, 0); + + // Apply a custom filter to show rows where Amount is between 80 and 180 (inclusive) + double lowerBound = 80.0; + double upperBound = 180.0; + worksheet.AutoFilter.Custom( + fieldIndex: 0, // Column A (Amount) + operatorType1: FilterOperatorType.GreaterOrEqual, + criteria1: lowerBound, + isAnd: true, // Combine with AND + operatorType2: FilterOperatorType.LessOrEqual, + criteria2: upperBound); + + // Refresh the filter to hide rows that do not meet the criteria + worksheet.AutoFilter.Refresh(); + + // Save the workbook + workbook.Save("FilteredAmounts.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/enable-the-tables-autofilter-feature-and-set-a-custom-criteria-that-filters-text-containing-a-specific-substring.cs b/working-with-tables/enable-the-tables-autofilter-feature-and-set-a-custom-criteria-that-filters-text-containing-a-specific-substring.cs new file mode 100644 index 0000000000..ca47c25f4c --- /dev/null +++ b/working-with-tables/enable-the-tables-autofilter-feature-and-set-a-custom-criteria-that-filters-text-containing-a-specific-substring.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableAutoFilter +{ + 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 (header + rows) + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Apple iPhone"); + sheet.Cells["B2"].PutValue("Electronics"); + sheet.Cells["A3"].PutValue("Banana Bread"); + sheet.Cells["B3"].PutValue("Food"); + sheet.Cells["A4"].PutValue("Apple MacBook"); + sheet.Cells["B4"].PutValue("Electronics"); + sheet.Cells["A5"].PutValue("Cherry Pie"); + sheet.Cells["B5"].PutValue("Food"); + + // Add a ListObject (table) covering the data range A1:B5 + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Enable auto‑filter for the table + table.HasAutoFilter = true; + + // Apply a custom filter on the first column (Product) to show rows containing "Apple" + // FilterOperatorType.Contains corresponds to the "contains" criterion + table.AutoFilter.Custom(0, FilterOperatorType.Contains, "Apple"); + table.AutoFilter.Refresh(); + + // Save the workbook + workbook.Save("TableAutoFilterContains.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/enable-the-tables-show-header-row-option-and-customize-the-header-font-color-for-emphasis.cs b/working-with-tables/enable-the-tables-show-header-row-option-and-customize-the-header-font-color-for-emphasis.cs new file mode 100644 index 0000000000..4e60824df3 --- /dev/null +++ b/working-with-tables/enable-the-tables-show-header-row-option-and-customize-the-header-font-color-for-emphasis.cs @@ -0,0 +1,64 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; +using System.Drawing; + +namespace AsposeCellsTableHeaderDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate header row and some sample data + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Price"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(1.20); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(0.80); + worksheet.Cells["A4"].PutValue("Orange"); + worksheet.Cells["B4"].PutValue(1.50); + + // Add a table (ListObject) that includes the header row + // Parameters: first row, first column, last row, last column, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Ensure the header row is visible + table.ShowHeaderRow = true; + + // Create a custom style for the header row + Style headerStyle = workbook.CreateStyle(); + headerStyle.Font.Color = Color.Red; // Emphasis color + headerStyle.Font.IsBold = true; // Optional bold for emphasis + headerStyle.Font.Size = 12; // Optional larger size + + // Define a custom table style name + string customStyleName = "CustomHeaderStyle"; + + // Access the collection of table styles in the workbook + TableStyleCollection tableStyles = workbook.Worksheets.TableStyles; + + // Add a new table style to the collection + int styleIdx = tableStyles.AddTableStyle(customStyleName); + TableStyle customTableStyle = tableStyles[styleIdx]; + + // Access the elements collection of the new style + TableStyleElementCollection elements = customTableStyle.TableStyleElements; + + // Add a HeaderRow element and assign the custom header style to it + int headerElementIdx = elements.Add(TableStyleElementType.HeaderRow); + elements[headerElementIdx].SetElementStyle(headerStyle); + + // Apply the custom style to the table + table.TableStyleName = customStyleName; + + // Save the workbook to a file + workbook.Save("TableWithHeaderStyle.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/export-a-specific-table-to-an-xml-file-using-the-excel-xml-schema-for-data-interchange.cs b/working-with-tables/export-a-specific-table-to-an-xml-file-using-the-excel-xml-schema-for-data-interchange.cs new file mode 100644 index 0000000000..708da5306d --- /dev/null +++ b/working-with-tables/export-a-specific-table-to-an-xml-file-using-the-excel-xml-schema-for-data-interchange.cs @@ -0,0 +1,97 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsExportTableToXml +{ + 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 that will be part of the table + sheet.Cells["A1"].PutValue("Id"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Charlie"); + + // Add a table (ListObject) covering the data range A1:B4 + int firstRow = 0; // zero‑based index for row 1 + int firstColumn = 0; // zero‑based index for column A + int totalRows = 4; + int totalColumns = 2; + + // Add returns the index of the created ListObject + int tableIdx = sheet.ListObjects.Add(firstRow, firstColumn, totalRows, totalColumns, true); + ListObject table = sheet.ListObjects[tableIdx]; + table.DisplayName = "PeopleTable"; + + // Define a simple XML schema that matches the table structure + string xmlSchema = @" + + + + + + + + + + + + + + + + "; + + // Add the XML map to the workbook using the schema + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "PeopleMap"; + + // Configure XML save options to export only the table range + XmlSaveOptions saveOptions = new XmlSaveOptions + { + ExportArea = new CellArea + { + StartRow = table.DataRange.FirstRow, + EndRow = table.DataRange.FirstRow + table.DataRange.RowCount - 1, + StartColumn = table.DataRange.FirstColumn, + EndColumn = table.DataRange.FirstColumn + table.DataRange.ColumnCount - 1 + }, + XmlMapName = xmlMap.Name, + SheetNameAsElementName = true, + DataAsAttribute = false + }; + + // Determine output path and ensure directory exists + string outputPath = "PeopleTableExport.xml"; + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook as an XML file using the configured options + workbook.Save(outputPath, saveOptions); + + Console.WriteLine($"Table exported successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/export-a-table-to-a-json-file-with-indentation-for-readability-and-include-column-headers-as-keys.cs b/working-with-tables/export-a-table-to-a-json-file-with-indentation-for-readability-and-include-column-headers-as-keys.cs new file mode 100644 index 0000000000..ea2fb87eb2 --- /dev/null +++ b/working-with-tables/export-a-table-to-a-json-file-with-indentation-for-readability-and-include-column-headers-as-keys.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; + +class ExportTableToJson +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate header row + worksheet.Cells["A1"].PutValue("Name"); + worksheet.Cells["B1"].PutValue("Age"); + worksheet.Cells["C1"].PutValue("City"); + + // Populate data rows + worksheet.Cells["A2"].PutValue("John"); + worksheet.Cells["B2"].PutValue(30); + worksheet.Cells["C2"].PutValue("New York"); + + worksheet.Cells["A3"].PutValue("Alice"); + worksheet.Cells["B3"].PutValue(25); + worksheet.Cells["C3"].PutValue("London"); + + // Set JSON export options: include headers and format with indentation + JsonSaveOptions jsonOptions = new JsonSaveOptions + { + HasHeaderRow = true, + Indent = " " // 4 spaces for readability + }; + + // Export the workbook (entire sheet) to a formatted JSON file + workbook.Save("TableExport.json", jsonOptions); + } +} \ No newline at end of file diff --git a/working-with-tables/export-a-table-to-an-html-file-preserving-table-structure-and-applying-inline-css-for-styling.cs b/working-with-tables/export-a-table-to-an-html-file-preserving-table-structure-and-applying-inline-css-for-styling.cs new file mode 100644 index 0000000000..a8a3e417b3 --- /dev/null +++ b/working-with-tables/export-a-table-to-an-html-file-preserving-table-structure-and-applying-inline-css-for-styling.cs @@ -0,0 +1,78 @@ +using System; +using System.Drawing; +using Aspose.Cells; + +namespace ExportTableToHtml +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate the worksheet with sample table data + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["C1"].PutValue("Price"); + + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["C2"].PutValue(0.5); + + sheet.Cells["A3"].PutValue("Banana"); + sheet.Cells["B3"].PutValue(5); + sheet.Cells["C3"].PutValue(0.3); + + sheet.Cells["A4"].PutValue("Cherry"); + sheet.Cells["B4"].PutValue(20); + sheet.Cells["C4"].PutValue(0.2); + + // Apply some styling to the header row + Style headerStyle = workbook.CreateStyle(); + headerStyle.Font.IsBold = true; + headerStyle.Font.Color = Color.White; + headerStyle.ForegroundColor = Color.DarkBlue; + headerStyle.Pattern = BackgroundType.Solid; + headerStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thick; + headerStyle.Borders[BorderType.BottomBorder].Color = Color.Black; + + // Apply the style to the header cells (A1:C1) + for (int col = 0; col < 3; col++) + { + sheet.Cells[0, col].SetStyle(headerStyle); + } + + // Apply border style to the data range + Style dataStyle = workbook.CreateStyle(); + dataStyle.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; + dataStyle.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; + dataStyle.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; + dataStyle.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; + + for (int row = 1; row <= 3; row++) + { + for (int col = 0; col < 3; col++) + { + sheet.Cells[row, col].SetStyle(dataStyle); + } + } + + // Configure HTML save options + HtmlSaveOptions htmlOptions = new HtmlSaveOptions(); + // Export only the table part (no extra worksheet UI) + htmlOptions.ExportDataOptions = HtmlExportDataOptions.Table; + // Use inline CSS styles instead of external CSS + htmlOptions.DisableCss = true; + // Do not export row/column headings + htmlOptions.ExportRowColumnHeadings = false; + + // Save the workbook as an HTML file with inline styling + string outputPath = "TableExport.html"; + workbook.Save(outputPath, htmlOptions); + + Console.WriteLine($"HTML file saved to: {outputPath}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/export-a-worksheet-containing-multiple-tables-to-a-single-pdf-file-preserving-each-tables-layout.cs b/working-with-tables/export-a-worksheet-containing-multiple-tables-to-a-single-pdf-file-preserving-each-tables-layout.cs new file mode 100644 index 0000000000..f49e985acc --- /dev/null +++ b/working-with-tables/export-a-worksheet-containing-multiple-tables-to-a-single-pdf-file-preserving-each-tables-layout.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; + +class ExportMultipleTablesToPdf +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + worksheet.Name = "Data"; + + // -------------------- First Table -------------------- + // Populate data for the first table (rows 0-9, columns A-B) + for (int i = 0; i < 10; i++) + { + worksheet.Cells[i, 0].PutValue($"Item {i + 1}"); + worksheet.Cells[i, 1].PutValue(i * 10); + } + + // Add the first table (ListObject) covering the populated range + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int firstTableIdx = worksheet.ListObjects.Add(0, 0, 9, 1, true); + worksheet.ListObjects[firstTableIdx].DisplayName = "FirstTable"; + + // -------------------- Second Table -------------------- + // Populate data for the second table (rows 12-19, columns D-E) + for (int i = 0; i < 8; i++) + { + worksheet.Cells[12 + i, 3].PutValue($"Product {i + 1}"); + worksheet.Cells[12 + i, 4].PutValue(i * 5); + } + + // Add the second table (ListObject) covering its range + int secondTableIdx = worksheet.ListObjects.Add(12, 3, 19, 4, true); + worksheet.ListObjects[secondTableIdx].DisplayName = "SecondTable"; + + // -------------------- PDF Save Options -------------------- + // Configure options to preserve the layout of each table. + // OnePagePerSheet = false allows the sheet to span multiple pages if needed. + // AllColumnsInOnePagePerSheet = false keeps column widths as defined. + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + OnePagePerSheet = false, + AllColumnsInOnePagePerSheet = false + }; + + // Save the workbook as a single PDF file containing both tables. + workbook.Save("MultipleTables.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/working-with-tables/export-a-worksheet-table-to-a-json-string-preserving-column-names-as-json-object-keys.cs b/working-with-tables/export-a-worksheet-table-to-a-json-string-preserving-column-names-as-json-object-keys.cs new file mode 100644 index 0000000000..6bd8ac7eea --- /dev/null +++ b/working-with-tables/export-a-worksheet-table-to-a-json-string-preserving-column-names-as-json-object-keys.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Utility; +using AsposeRange = Aspose.Cells.Range; + +namespace AsposeCellsJsonExport +{ + class Program + { + 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 the worksheet with a header row and some data rows + cells["A1"].PutValue("Name"); + cells["B1"].PutValue("Age"); + cells["C1"].PutValue("City"); + + cells["A2"].PutValue("John"); + cells["B2"].PutValue(30); + cells["C2"].PutValue("New York"); + + cells["A3"].PutValue("Alice"); + cells["B3"].PutValue(25); + cells["C3"].PutValue("London"); + + cells["A4"].PutValue("Bob"); + cells["B4"].PutValue(28); + cells["C4"].PutValue("Paris"); + + // Define the range that includes the header and all data rows + // start row = 0, start column = 0, total rows = 4, total columns = 3 + AsposeRange exportRange = cells.CreateRange(0, 0, 4, 3); + + // Configure JSON export options + JsonSaveOptions jsonOptions = new JsonSaveOptions + { + HasHeaderRow = true, // first row contains column names + ExportEmptyCells = true, // export empty cells as null + Indent = " " // pretty‑print with 4 spaces + }; + + // Export the defined range to a JSON string + string jsonResult = JsonUtility.ExportRangeToJson(exportRange, jsonOptions); + + // Output the JSON string to the console + Console.WriteLine("Exported JSON:"); + Console.WriteLine(jsonResult); + } + catch (Exception ex) + { + // Log the exception details + Console.Error.WriteLine($"Error: {ex.Message}"); + Console.Error.WriteLine(ex.StackTrace); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/export-all-tables-in-a-workbook-to-separate-csv-files-naming-each-file-after-its-corresponding-table-name.cs b/working-with-tables/export-all-tables-in-a-workbook-to-separate-csv-files-naming-each-file-after-its-corresponding-table-name.cs new file mode 100644 index 0000000000..2293806650 --- /dev/null +++ b/working-with-tables/export-all-tables-in-a-workbook-to-separate-csv-files-naming-each-file-after-its-corresponding-table-name.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // For ListObject +using AsposeRange = Aspose.Cells.Range; // Alias to avoid conflict with System.Range + +namespace ExportTablesToCsv +{ + class Program + { + static void Main() + { + // Path to the source workbook containing tables + string sourcePath = "input.xlsx"; + + // Verify that the source file exists to avoid FileNotFoundException + if (!File.Exists(sourcePath)) + { + Console.WriteLine($"Source file not found: {sourcePath}"); + return; + } + + try + { + // Load the workbook inside a using block for deterministic disposal + using (Workbook sourceWorkbook = new Workbook(sourcePath)) + { + // Iterate through each worksheet + foreach (Worksheet sheet in sourceWorkbook.Worksheets) + { + // Iterate through each table (ListObject) in the worksheet + foreach (ListObject table in sheet.ListObjects) + { + try + { + // Create a temporary workbook to hold the single table + using (Workbook tempWorkbook = new Workbook()) + { + // Get the first (and only) worksheet of the temporary workbook + Worksheet tempSheet = tempWorkbook.Worksheets[0]; + + // Determine the size of the table's data range (including header) + int rows = table.DataRange.RowCount; + int cols = table.DataRange.ColumnCount; + + // Create a destination range in the temporary sheet starting at A1 + AsposeRange destRange = tempSheet.Cells.CreateRange(0, 0, rows, cols); + + // Copy the table's data range to the destination range + table.DataRange.Copy(destRange); + + // Prepare CSV save options – export only the active sheet + TxtSaveOptions csvOptions = new TxtSaveOptions(SaveFormat.Csv) + { + ExportAllSheets = false + }; + + // Use the table's display name for the output file (fallback to a GUID if empty) + string tableName = !string.IsNullOrEmpty(table.DisplayName) ? table.DisplayName : $"Table_{Guid.NewGuid():N}"; + string outputFileName = $"{tableName}.csv"; + + // Save the temporary workbook as a CSV file + tempWorkbook.Save(outputFileName, csvOptions); + Console.WriteLine($"Exported table '{tableName}' to '{outputFileName}'."); + } + } + catch (Exception exTable) + { + Console.WriteLine($"Failed to export table '{table.DisplayName}': {exTable.Message}"); + } + } + } + } + + Console.WriteLine("All tables have been processed."); + } + catch (Exception ex) + { + // Catch any runtime exceptions and display a friendly message + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/export-the-data-from-a-query-table-to-a-csv-file-while-preserving-column-headers-and-data-types.cs b/working-with-tables/export-the-data-from-a-query-table-to-a-csv-file-while-preserving-column-headers-and-data-types.cs new file mode 100644 index 0000000000..7410cf1007 --- /dev/null +++ b/working-with-tables/export-the-data-from-a-query-table-to-a-csv-file-while-preserving-column-headers-and-data-types.cs @@ -0,0 +1,102 @@ +using System; +using System.Data; +using System.Globalization; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class ExportQueryTableToCsv +{ + 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 the worksheet with sample data (including headers) + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + cells["C1"].PutValue("Amount"); + cells["D1"].PutValue("Date"); + + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["C2"].PutValue(123.45); + cells["D2"].PutValue(new DateTime(2023, 1, 15)); + + cells["A3"].PutValue(2); + cells["B3"].PutValue("Bob"); + cells["C3"].PutValue(678.90); + cells["D3"].PutValue(new DateTime(2023, 2, 20)); + + // Define a ListObject (query table) that covers the data range + int totalRows = 3; // header + 2 data rows + int totalCols = 4; // four columns + int listObjectIndex = worksheet.ListObjects.Add(0, 0, totalRows, totalCols, true); + ListObject table = worksheet.ListObjects[listObjectIndex]; + table.DisplayName = "SampleTable"; + + // Configure export options to preserve column headers and original data types + ExportTableOptions exportOptions = new ExportTableOptions + { + ExportColumnName = true, // first row becomes DataTable column names + ExportAsString = false, // keep original .NET types + CheckMixedValueType = true // verify mixed types and fallback to string if needed + }; + + // Export the ListObject's data range to a DataTable using the options above + DataTable dataTable = table.DataRange.ExportDataTable(exportOptions); + + // Write the DataTable to a CSV file while preserving data types in the output format + string csvFilePath = "QueryTableExport.csv"; + using (StreamWriter writer = new StreamWriter(csvFilePath)) + { + // Write CSV header + for (int col = 0; col < dataTable.Columns.Count; col++) + { + writer.Write(dataTable.Columns[col].ColumnName); + if (col < dataTable.Columns.Count - 1) writer.Write(","); + } + writer.WriteLine(); + + // Write each DataRow + foreach (DataRow row in dataTable.Rows) + { + for (int col = 0; col < dataTable.Columns.Count; col++) + { + object value = row[col]; + + // Preserve formatting for dates and numeric types + if (value is DateTime dtValue) + { + // ISO 8601 format for dates + writer.Write(dtValue.ToString("o", CultureInfo.InvariantCulture)); + } + else if (value is IFormattable fmtValue) + { + // Use invariant culture for numbers to avoid locale issues + writer.Write(fmtValue.ToString(null, CultureInfo.InvariantCulture)); + } + else + { + writer.Write(value?.ToString() ?? string.Empty); + } + + if (col < dataTable.Columns.Count - 1) writer.Write(","); + } + writer.WriteLine(); + } + } + + // Save the workbook (optional, for verification) + workbook.Save("WorkbookWithQueryTable.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/generate-a-pivot-table-based-on-an-existing-worksheet-table-and-place-it-on-a-new-worksheet.cs b/working-with-tables/generate-a-pivot-table-based-on-an-existing-worksheet-table-and-place-it-on-a-new-worksheet.cs new file mode 100644 index 0000000000..cfcef889e6 --- /dev/null +++ b/working-with-tables/generate-a-pivot-table-based-on-an-existing-worksheet-table-and-place-it-on-a-new-worksheet.cs @@ -0,0 +1,84 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsPivotExample +{ + public class CreatePivotFromTable + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // ---------- Source worksheet with data and a table ---------- + Worksheet sourceSheet = workbook.Worksheets[0]; + sourceSheet.Name = "SourceData"; + + // Populate sample data + sourceSheet.Cells["A1"].PutValue("Category"); + sourceSheet.Cells["B1"].PutValue("Product"); + sourceSheet.Cells["C1"].PutValue("Sales"); + + for (int i = 2; i <= 10; i++) + { + sourceSheet.Cells[$"A{i}"].PutValue("Cat" + ((i % 3) + 1)); + sourceSheet.Cells[$"B{i}"].PutValue("Prod" + i); + sourceSheet.Cells[$"C{i}"].PutValue(i * 100); + } + + // Define a table (ListObject) over the data range + int firstDataRow = 0; // zero‑based index + int firstDataColumn = 0; + int totalRows = sourceSheet.Cells.MaxDisplayRange.RowCount; + int totalColumns = sourceSheet.Cells.MaxDisplayRange.ColumnCount; + + int tableIndex = sourceSheet.ListObjects.Add(firstDataRow, firstDataColumn, + totalRows - 1, totalColumns - 1, true); + ListObject table = sourceSheet.ListObjects[tableIndex]; + // Set the table name (use DisplayName as Name is not available in this version) + table.DisplayName = "SalesTable"; + + // ---------- Destination worksheet for the pivot table ---------- + Worksheet pivotSheet = workbook.Worksheets.Add("PivotTable"); + + // Build the source data reference using the table name + // For a table, the reference format is: =SheetName!TableName + string sourceData = $"=SourceData!{table.DisplayName}"; + + // Add a new pivot table to the destination sheet (cell A1, name "SalesPivot") + int pivotIndex = pivotSheet.PivotTables.Add(sourceData, "A1", "SalesPivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIndex]; + + // Configure pivot fields + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); // Row field + pivotTable.AddFieldToArea(PivotFieldType.Column, "Product"); // Column field + pivotTable.AddFieldToArea(PivotFieldType.Data, "Sales"); // Data field (sum) + + // Refresh the pivot table to calculate data + pivotSheet.RefreshPivotTables(); + + // Save the workbook + string outputPath = "PivotFromTableDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point required by the project + public class Program + { + public static void Main(string[] args) + { + CreatePivotFromTable.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/generate-a-summary-worksheet-that-aggregates-values-from-multiple-tables-using-structured-reference-formulas.cs b/working-with-tables/generate-a-summary-worksheet-that-aggregates-values-from-multiple-tables-using-structured-reference-formulas.cs new file mode 100644 index 0000000000..47e02df45c --- /dev/null +++ b/working-with-tables/generate-a-summary-worksheet-that-aggregates-values-from-multiple-tables-using-structured-reference-formulas.cs @@ -0,0 +1,98 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsSummaryExample +{ + class Program + { + static void Main() + { + try + { + // ---------- Create a new workbook ---------- + Workbook workbook = new Workbook(); + + // ---------- Populate first worksheet with Table1 ---------- + Worksheet sheet1 = workbook.Worksheets[0]; + sheet1.Name = "SalesData"; + + // Header row + sheet1.Cells["A1"].PutValue("Region"); + sheet1.Cells["B1"].PutValue("Amount"); + + // Sample data + sheet1.Cells["A2"].PutValue("North"); + sheet1.Cells["B2"].PutValue(1200); + sheet1.Cells["A3"].PutValue("South"); + sheet1.Cells["B3"].PutValue(850); + sheet1.Cells["A4"].PutValue("East"); + sheet1.Cells["B4"].PutValue(970); + sheet1.Cells["A5"].PutValue("West"); + sheet1.Cells["B5"].PutValue(660); + + // Convert range A1:B5 to a table (ListObject) named Table1 + int table1Index = sheet1.ListObjects.Add(0, 0, 4, 1, true); + ListObject table1 = sheet1.ListObjects[table1Index]; + table1.DisplayName = "Table1"; // Set table name + + // ---------- Populate second worksheet with Table2 ---------- + Worksheet sheet2 = workbook.Worksheets.Add("ExpenseData"); + + // Header row + sheet2.Cells["A1"].PutValue("Category"); + sheet2.Cells["B1"].PutValue("Amount"); + + // Sample data + sheet2.Cells["A2"].PutValue("Travel"); + sheet2.Cells["B2"].PutValue(300); + sheet2.Cells["A3"].PutValue("Supplies"); + sheet2.Cells["B3"].PutValue(150); + sheet2.Cells["A4"].PutValue("Utilities"); + sheet2.Cells["B4"].PutValue(200); + sheet2.Cells["A5"].PutValue("Misc"); + sheet2.Cells["B5"].PutValue(100); + + // Convert range A1:B5 to a table (ListObject) named Table2 + int table2Index = sheet2.ListObjects.Add(0, 0, 4, 1, true); + ListObject table2 = sheet2.ListObjects[table2Index]; + table2.DisplayName = "Table2"; // Set table name + + // ---------- Create Summary worksheet ---------- + Worksheet summary = workbook.Worksheets.Add("Summary"); + + // Labels + summary.Cells["A1"].PutValue("Summary of Amounts"); + summary.Cells["A3"].PutValue("Total Sales (Table1)"); + summary.Cells["A4"].PutValue("Total Expenses (Table2)"); + summary.Cells["A5"].PutValue("Grand Total"); + + // Structured reference formulas + summary.Cells["B3"].Formula = "=SUM(Table1[Amount])"; + summary.Cells["B4"].Formula = "=SUM(Table2[Amount])"; + summary.Cells["B5"].Formula = "=B3+B4"; + + // Calculate formulas so values are stored + workbook.CalculateFormula(); + + // ---------- Save the workbook ---------- + string outputPath = "SummaryWorkbook.xlsx"; + + // Ensure the directory exists before saving + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + 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/working-with-tables/group-rows-within-the-table-based-on-category-column-and-collapse-the-groups-for-compact-view.cs b/working-with-tables/group-rows-within-the-table-based-on-category-column-and-collapse-the-groups-for-compact-view.cs new file mode 100644 index 0000000000..61bc75fd72 --- /dev/null +++ b/working-with-tables/group-rows-within-the-table-based-on-category-column-and-collapse-the-groups-for-compact-view.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class GroupRowsByCategory + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Header + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Value"); + + // Sample data + string[] categories = { "Alpha", "Alpha", "Alpha", "Beta", "Beta", "Gamma", "Gamma", "Gamma", "Gamma" }; + int[] values = { 10, 15, 20, 30, 35, 40, 45, 50, 55 }; + + for (int i = 0; i < categories.Length; i++) + { + int rowIndex = i + 1; // +1 because row 0 is header + cells[rowIndex, 0].PutValue(categories[i]); // Column A + cells[rowIndex, 1].PutValue(values[i]); // Column B + } + + // Group rows by consecutive identical categories + int startRow = 1; // first data row (zero‑based index) + string currentCategory = cells[startRow, 0].StringValue; + + for (int row = startRow + 1; row <= categories.Length; row++) + { + bool isEnd = row == categories.Length; + string nextCategory = isEnd ? null : cells[row, 0].StringValue; + + if (isEnd || nextCategory != currentCategory) + { + int endRow = row - 1; // last row of the current group + + // Group only if the group has more than one row + if (endRow > startRow) + { + cells.GroupRows(startRow, endRow, true); + } + + // Prepare for the next group + if (!isEnd) + { + startRow = row; + currentCategory = nextCategory; + } + } + } + + // Show summary row above details (compact view) + worksheet.Outline.SummaryRowBelow = false; + + // Save the workbook + string outputPath = "GroupedByCategory.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + GroupRowsByCategory.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/hide-a-table-column-programmatically-and-later-unhide-it-based-on-user-interaction-criteria.cs b/working-with-tables/hide-a-table-column-programmatically-and-later-unhide-it-based-on-user-interaction-criteria.cs new file mode 100644 index 0000000000..518f224260 --- /dev/null +++ b/working-with-tables/hide-a-table-column-programmatically-and-later-unhide-it-based-on-user-interaction-criteria.cs @@ -0,0 +1,42 @@ +using System; +using Aspose.Cells; + +class HideUnhideColumnDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Add sample data to column B (zero‑based index 1) + cells["B1"].PutValue("This column will be hidden"); + cells["B2"].PutValue(123); + cells["B3"].PutValue(456); + + // Hide column B + cells.HideColumn(1); + + // Save the workbook with the hidden column + workbook.Save("HiddenColumn.xlsx"); + + Console.WriteLine("Column B is hidden. Press 'U' to unhide it, any other key to exit."); + var key = Console.ReadKey(); + Console.WriteLine(); + + if (key.KeyChar == 'U' || key.KeyChar == 'u') + { + // Unhide column B; width -1 uses the standard column width + cells.UnhideColumn(1, -1); + + // Save the workbook after unhiding + workbook.Save("UnhiddenColumn.xlsx"); + Console.WriteLine("Column B has been unhidden and saved as UnhiddenColumn.xlsx"); + } + else + { + Console.WriteLine("No changes made. The workbook remains with the hidden column."); + } + } +} \ No newline at end of file diff --git a/working-with-tables/hide-the-table-header-row-while-keeping-the-data-rows-visible-for-reporting-purposes.cs b/working-with-tables/hide-the-table-header-row-while-keeping-the-data-rows-visible-for-reporting-purposes.cs new file mode 100644 index 0000000000..e46cba65c1 --- /dev/null +++ b/working-with-tables/hide-the-table-header-row-while-keeping-the-data-rows-visible-for-reporting-purposes.cs @@ -0,0 +1,39 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace HideTableHeaderDemo +{ + 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 (including a header row) + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(30); + + // Add a ListObject (table) covering the data range (including header) + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Apply a style (optional) + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Hide the header row while keeping data rows visible + table.ShowHeaderRow = false; + + // Save the workbook to a file + workbook.Save("HideTableHeaderDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/import-a-json-array-into-a-table-automatically-creating-rows-and-mapping-json-fields-to-columns.cs b/working-with-tables/import-a-json-array-into-a-table-automatically-creating-rows-and-mapping-json-fields-to-columns.cs new file mode 100644 index 0000000000..a362e7b932 --- /dev/null +++ b/working-with-tables/import-a-json-array-into-a-table-automatically-creating-rows-and-mapping-json-fields-to-columns.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Utility; + +class Program +{ + static void Main() + { + // Sample JSON array where each object will become a row and its properties become columns + string json = @"[ + { ""Name"": ""John"", ""Age"": 30, ""City"": ""New York"" }, + { ""Name"": ""Jane"", ""Age"": 25, ""City"": ""London"" }, + { ""Name"": ""Bob"", ""Age"": 40, ""City"": ""Paris"" } + ]"; + + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Configure layout options to treat the JSON array as a table + JsonLayoutOptions options = new JsonLayoutOptions + { + ArrayAsTable = true // Enables automatic row creation and column mapping + }; + + // Import the JSON data starting at cell A1 (row index 0, column index 0) + JsonUtility.ImportData(json, worksheet.Cells, 0, 0, options); + + // Save the workbook to an Excel file + workbook.Save("JsonArrayTable.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/import-an-html-table-into-a-worksheet-converting-it-into-a-structured-table-with-proper-column-headers.cs b/working-with-tables/import-an-html-table-into-a-worksheet-converting-it-into-a-structured-table-with-proper-column-headers.cs new file mode 100644 index 0000000000..c8e1911014 --- /dev/null +++ b/working-with-tables/import-an-html-table-into-a-worksheet-converting-it-into-a-structured-table-with-proper-column-headers.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; + +class ImportHtmlTable +{ + static void Main() + { + // Create an empty workbook + Workbook workbook = new Workbook(); + + // Configure HTML load options + HtmlLoadOptions loadOptions = new HtmlLoadOptions(); + + // Define a table load option: + // - Import the first table (index 0) from the HTML + // - Convert it to a ListObject (structured table) so column headers are recognized + HtmlTableLoadOption tableOption = new HtmlTableLoadOption + { + TableIndex = 0, + TableToListObject = true + }; + + // Add the option to the collection + loadOptions.TableLoadOptions.Add(tableOption); + + // Load the HTML file with the specified options + workbook = new Workbook("input.html", loadOptions); + + // Save the workbook as an Excel file + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/import-data-from-a-csv-file-into-a-new-table-and-automatically-detect-column-data-types-during-import.cs b/working-with-tables/import-data-from-a-csv-file-into-a-new-table-and-automatically-detect-column-data-types-during-import.cs new file mode 100644 index 0000000000..67edda8d1a --- /dev/null +++ b/working-with-tables/import-data-from-a-csv-file-into-a-new-table-and-automatically-detect-column-data-types-during-import.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsCsvImportExample +{ + class Program + { + static void Main() + { + try + { + // Path to the CSV file (replace with your actual file path) + string csvPath = "data.csv"; + + // Verify that the CSV file exists to avoid FileNotFoundException + if (!File.Exists(csvPath)) + { + Console.WriteLine($"CSV file not found: {csvPath}"); + return; + } + + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Configure CSV load options to automatically detect numeric and date values + TxtLoadOptions loadOptions = new TxtLoadOptions + { + Separator = ',', // CSV delimiter + ConvertNumericData = true, // Convert numeric strings to numbers + ConvertDateTimeData = true, // Convert date strings to DateTime + ParsingFormulaOnOpen = false // Not needed for plain CSV + }; + + // Import CSV data starting at cell A1 (row 0, column 0) + cells.ImportCSV(csvPath, loadOptions, 0, 0); + + // Determine the range that contains the imported data + int lastRow = cells.MaxDataRow; + int lastColumn = cells.MaxDataColumn; + + // Create a table (ListObject) from the imported range + // The 'true' parameter indicates that the first row contains column headers + int tableIndex = worksheet.ListObjects.Add(0, 0, lastRow + 1, lastColumn + 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "ImportedCsvTable"; + + // Save the workbook with the new table + string outputPath = "ImportedCsvWithTable.xlsx"; + workbook.Save(outputPath, SaveFormat.Xlsx); + 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/working-with-tables/import-data-from-an-xml-file-into-a-new-table-mapping-xml-elements-to-table-columns-automatically.cs b/working-with-tables/import-data-from-an-xml-file-into-a-new-table-mapping-xml-elements-to-table-columns-automatically.cs new file mode 100644 index 0000000000..b9a9d14243 --- /dev/null +++ b/working-with-tables/import-data-from-an-xml-file-into-a-new-table-mapping-xml-elements-to-table-columns-automatically.cs @@ -0,0 +1,19 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Import the XML file into the first worksheet. + // The XML elements are automatically mapped to table columns. + // Parameters: XML file path, destination sheet name, start row (0‑based), start column (0‑based) + workbook.ImportXml("data.xml", "Sheet1", 0, 0); + + // Save the workbook with the imported data + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/import-json-data-into-a-new-table-automatically-creating-columns-based-on-json-object-properties.cs b/working-with-tables/import-json-data-into-a-new-table-automatically-creating-columns-based-on-json-object-properties.cs new file mode 100644 index 0000000000..385823ba62 --- /dev/null +++ b/working-with-tables/import-json-data-into-a-new-table-automatically-creating-columns-based-on-json-object-properties.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Utility; + +namespace AsposeCellsJsonImportExample +{ + public class JsonImportDemo + { + public static void Run() + { + try + { + // Sample JSON array; each object becomes a row, properties become columns + string json = @"[ + { ""Name"": ""Alice"", ""Age"": 30, ""Country"": ""USA"" }, + { ""Name"": ""Bob"", ""Age"": 25, ""Country"": ""Canada"" }, + { ""Name"": ""Charlie"", ""Age"": 28, ""Country"": ""UK"" } + ]"; + + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Configure layout to treat the JSON array as a table + JsonLayoutOptions options = new JsonLayoutOptions + { + ArrayAsTable = true + }; + + // Import JSON data starting at cell A1 (row 0, column 0) + JsonUtility.ImportData(json, worksheet.Cells, 0, 0, options); + + // Save the workbook + string outputPath = "JsonImportedTable.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + JsonImportDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/insert-a-calculated-total-value-at-the-bottom-of-a-table-using-listobjectputcellvalue-with-appropriate-offsets.cs b/working-with-tables/insert-a-calculated-total-value-at-the-bottom-of-a-table-using-listobjectputcellvalue-with-appropriate-offsets.cs new file mode 100644 index 0000000000..e76e28c3e9 --- /dev/null +++ b/working-with-tables/insert-a-calculated-total-value-at-the-bottom-of-a-table-using-listobjectputcellvalue-with-appropriate-offsets.cs @@ -0,0 +1,65 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTotalExample +{ + 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 with a header and numeric values + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Amount"); + cells["A2"].PutValue("A"); + cells["B2"].PutValue(120); + cells["A3"].PutValue("B"); + cells["B3"].PutValue(80); + cells["A4"].PutValue("C"); + cells["B4"].PutValue(150); + + // Define the range of the table (including header and data rows) + int startRow = 0; // Row 0 -> A1 + int startColumn = 0; // Column 0 -> A + int endRow = 3; // Row 3 -> A4/B4 (last data row) + int endColumn = 1; // Column 1 -> B + + // Add the ListObject (table) to the worksheet + int tableIndex = sheet.ListObjects.Add(startRow, startColumn, endRow, endColumn, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Enable the totals row; Aspose.Cells will add an extra row after the data rows + table.ShowTotals = true; + + // Calculate the sum of the "Amount" column (column index 1) manually + double sum = 0; + // Data rows are from row offset 1 (first data row) to (table.EndRow - table.StartRow - 1) (excluding totals row) + int dataRowCount = table.EndRow - table.StartRow; // includes totals row, so subtract 1 for data rows + for (int i = 1; i < dataRowCount; i++) // start at 1 to skip header row + { + // Retrieve the cell value from the worksheet using absolute coordinates + object val = cells[table.StartRow + i, table.StartColumn + 1].Value; + if (val is double d) sum += d; + else if (val is int n) sum += n; + } + + // Determine the offset for the totals row (last row of the table) + int totalsRowOffset = table.EndRow - table.StartRow; // zero‑based offset; points to the totals row + int amountColumnOffset = 1; // second column in the table + + // Insert the calculated total value into the totals row using PutCellValue + table.PutCellValue(totalsRowOffset, amountColumnOffset, sum); + + // Optionally, set a label for the totals row in the first column + table.PutCellValue(totalsRowOffset, 0, "Grand Total", true); + + // Save the workbook + workbook.Save("TableWithCalculatedTotal.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/insert-a-formula-into-a-table-cell-using-cellputvalue-with-a-formula-string.cs b/working-with-tables/insert-a-formula-into-a-table-cell-using-cellputvalue-with-a-formula-string.cs new file mode 100644 index 0000000000..18bb8d1bfa --- /dev/null +++ b/working-with-tables/insert-a-formula-into-a-table-cell-using-cellputvalue-with-a-formula-string.cs @@ -0,0 +1,50 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class InsertFormulaIntoTableCell +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook wb = new Workbook(); + Worksheet ws = wb.Worksheets[0]; + Cells cells = ws.Cells; + + // Add header row + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Value"); + cells["C1"].PutValue("Formula"); + + // Add some sample data + cells["A2"].PutValue(1); + cells["B2"].PutValue(10); + cells["A3"].PutValue(2); + cells["B3"].PutValue(20); + + // Create a table that spans A1:C3 + int tableIndex = ws.ListObjects.Add("A1", "C3", true); + ListObject table = ws.ListObjects[tableIndex]; + + // Append a new row to the table (row offset 3, because header is row 0) + table.PutCellValue(3, 0, 3); // ID column + table.PutCellValue(3, 1, 30); // Value column + + // Get the cell object for the Formula column in the newly added row + // Row index 3 (fourth row), column index 2 (C column) + Cell formulaCell = cells[3, 2]; + + // Insert a formula using PutValue with a formula string. + // The string starts with '=' so Excel treats it as a formula. + formulaCell.PutValue("=B4*2"); // B4 corresponds to the Value column of the new row + + // Recalculate the workbook so the formula result is evaluated + wb.CalculateFormula(); + + // Display the calculated result + Console.WriteLine("Result in C4 (Formula column): " + formulaCell.Value); + + // Save the workbook + wb.Save("TableWithFormula.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-a-multi-line-string-into-a-table-cell-using-listobjectputcellvalue-with-newline-characters.cs b/working-with-tables/insert-a-multi-line-string-into-a-table-cell-using-listobjectputcellvalue-with-newline-characters.cs new file mode 100644 index 0000000000..bc0f1aa21c --- /dev/null +++ b/working-with-tables/insert-a-multi-line-string-into-a-table-cell-using-listobjectputcellvalue-with-newline-characters.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class InsertMultiLineStringIntoTableCell +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Add header row and a sample data row to define the table range + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Description"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Initial"); + + // Create a ListObject (Excel table) that includes the header and data rows + int tableIndex = worksheet.ListObjects.Add("A1", "B2", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Multi‑line string using newline characters + string multiLineText = "Line 1\nLine 2\nLine 3"; + + // Insert the multi‑line string into the first data row (row offset 1) and second column (column offset 1) + table.PutCellValue(1, 1, multiLineText); + + // Save the workbook to a file + workbook.Save("MultiLineTableCell.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/insert-a-new-row-into-a-table-and-automatically-copy-the-formatting-from-the-previous-row.cs b/working-with-tables/insert-a-new-row-into-a-table-and-automatically-copy-the-formatting-from-the-previous-row.cs new file mode 100644 index 0000000000..6089621a7e --- /dev/null +++ b/working-with-tables/insert-a-new-row-into-a-table-and-automatically-copy-the-formatting-from-the-previous-row.cs @@ -0,0 +1,61 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +namespace AsposeCellsInsertRowInTable +{ + class Program + { + 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 a table (A1:B3) + cells["A1"].PutValue("Header1"); + cells["B1"].PutValue("Header2"); + cells["A2"].PutValue("Item1"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Item2"); + cells["B3"].PutValue(20); + + // Apply a simple style to the header row (bold font) + Style headerStyle = workbook.CreateStyle(); + headerStyle.Font.IsBold = true; + StyleFlag headerFlag = new StyleFlag { FontBold = true }; + cells.ApplyRowStyle(0, headerStyle, headerFlag); + + // Convert the range A1:B3 into a table (ListObject) + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "SampleTable"; + + // Insert a new row at index 2 (third row, zero‑based) and copy formatting from the row above + InsertOptions insertOptions = new InsertOptions + { + CopyFormatType = CopyFormatType.SameAsAbove, + UpdateReference = true + }; + // Row index 2 corresponds to the position just after the header and first data row + cells.InsertRows(2, 1, insertOptions); + + // Optionally, add data to the newly inserted row + cells["A3"].PutValue("NewItem"); + cells["B3"].PutValue(30); + + // Save the workbook + string outputPath = "TableWithInsertedRow.xlsx"; + 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/working-with-tables/iterate-through-all-tables-in-a-workbook-and-convert-each-to-a-range-with-custom-tabletorangeoptions.cs b/working-with-tables/iterate-through-all-tables-in-a-workbook-and-convert-each-to-a-range-with-custom-tabletorangeoptions.cs new file mode 100644 index 0000000000..cb976a1846 --- /dev/null +++ b/working-with-tables/iterate-through-all-tables-in-a-workbook-and-convert-each-to-a-range-with-custom-tabletorangeoptions.cs @@ -0,0 +1,41 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableToRange +{ + class Program + { + static void Main(string[] args) + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through each worksheet in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + // Get the collection of tables (ListObjects) on the current worksheet + ListObjectCollection tables = sheet.ListObjects; + + // Iterate backwards because ConvertToRange removes the table from the collection + for (int i = tables.Count - 1; i >= 0; i--) + { + ListObject table = tables[i]; + + // Create custom options for conversion + TableToRangeOptions options = new TableToRangeOptions(); + + // Example: set the last row to the current end row of the table. + // This demonstrates using a custom option; adjust as needed. + options.LastRow = table.EndRow; + + // Convert the table to a normal range using the options + table.ConvertToRange(options); + } + } + + // Save the modified workbook (replace with your desired output path) + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/load-a-workbook-and-convert-a-specific-table-to-a-range-preserving-formatting-up-to-row-ten.cs b/working-with-tables/load-a-workbook-and-convert-a-specific-table-to-a-range-preserving-formatting-up-to-row-ten.cs new file mode 100644 index 0000000000..9657abe697 --- /dev/null +++ b/working-with-tables/load-a-workbook-and-convert-a-specific-table-to-a-range-preserving-formatting-up-to-row-ten.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class ConvertTableToRange +{ + static void Main() + { + // Load the workbook from file + Workbook workbook = new Workbook("input.xlsx"); + + // Get the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure there is at least one table (ListObject) on the sheet + if (sheet.ListObjects.Count == 0) + { + Console.WriteLine("No tables found in the worksheet."); + return; + } + + // Retrieve the first table + ListObject table = sheet.ListObjects[0]; + + // Define conversion options: convert only up to row 10 (zero‑based index 9) + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = 9 + }; + + // Convert the table to a normal range while preserving formatting + table.ConvertToRange(options); + + // Save the workbook with the changes + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/load-a-workbook-locate-a-table-by-name-and-export-its-contents-to-an-html-fragment.cs b/working-with-tables/load-a-workbook-locate-a-table-by-name-and-export-its-contents-to-an-html-fragment.cs new file mode 100644 index 0000000000..55bdab7f06 --- /dev/null +++ b/working-with-tables/load-a-workbook-locate-a-table-by-name-and-export-its-contents-to-an-html-fragment.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Tables; // For ListObject +using AsposeRange = Aspose.Cells.Range; // Alias to avoid conflict with System.Range + +class ExportTableToHtmlFragment +{ + static void Main() + { + try + { + // Path to the source Excel workbook + string workbookPath = "input.xlsx"; + + // Verify that the file exists before loading + if (!File.Exists(workbookPath)) + { + Console.WriteLine($"File not found: {workbookPath}"); + return; + } + + // Load the workbook from the file + Workbook workbook = new Workbook(workbookPath); + + // Assume the table is in the first worksheet; adjust as needed + Worksheet worksheet = workbook.Worksheets[0]; + + // Locate the table (ListObject) by its name + // Replace "MyTable" with the actual table name in the workbook + ListObject table = worksheet.ListObjects["MyTable"]; + if (table == null) + { + Console.WriteLine("Table 'MyTable' not found in the worksheet."); + return; + } + + // Determine the cell area that contains the table data + AsposeRange dataRange = table.DataRange; + int startRow = dataRange.FirstRow; + int startColumn = dataRange.FirstColumn; + int endRow = startRow + dataRange.RowCount - 1; + int endColumn = startColumn + dataRange.ColumnCount - 1; + + CellArea exportArea = CellArea.CreateCellArea(startRow, startColumn, endRow, endColumn); + + // Configure HTML save options to export only the table part + HtmlSaveOptions htmlOptions = new HtmlSaveOptions + { + ExportDataOptions = HtmlExportDataOptions.Table, + ExportArea = exportArea + }; + + // Save the selected area to a memory stream as HTML + using (MemoryStream ms = new MemoryStream()) + { + workbook.Save(ms, htmlOptions); + ms.Position = 0; + + // Convert the HTML bytes to a string (HTML fragment) + string htmlFragment = Encoding.UTF8.GetString(ms.ToArray()); + + // Output the HTML fragment + Console.WriteLine(htmlFragment); + } + } + catch (Exception ex) + { + // Runtime safety: report any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/load-a-workbook-retrieve-a-table-via-cellgettable-and-read-its-display-name-property.cs b/working-with-tables/load-a-workbook-retrieve-a-table-via-cellgettable-and-read-its-display-name-property.cs new file mode 100644 index 0000000000..7747023a21 --- /dev/null +++ b/working-with-tables/load-a-workbook-retrieve-a-table-via-cellgettable-and-read-its-display-name-property.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class GetTableDisplayNameDemo + { + // Entry point for the application + public static void Main() + { + Run(); + } + + public static void Run() + { + const string inputPath = "input.xlsx"; + + try + { + // Verify that the input file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing workbook + Workbook workbook = new Workbook(inputPath); + + // Access the first worksheet (adjust index if needed) + Worksheet worksheet = workbook.Worksheets[0]; + + // Choose a cell that belongs to a table (ensure A1 is inside a table) + Cell cell = worksheet.Cells["A1"]; + + // Retrieve the table (ListObject) that the cell belongs to + ListObject table = cell.GetTable(); + + if (table != null) + { + // Read and output the display name of the table + Console.WriteLine("Table Display Name: " + table.DisplayName); + } + else + { + Console.WriteLine("The specified cell does not belong to any table."); + } + + // Optionally save the workbook if any changes were made + // workbook.Save("output.xlsx"); + } + catch (Exception ex) + { + // Catch any unexpected errors and display a message + Console.WriteLine("An error occurred: " + ex.Message); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/load-an-existing-excel-workbook-containing-query-tables-and-enumerate-all-tables-linked-to-external-data-sources.cs b/working-with-tables/load-an-existing-excel-workbook-containing-query-tables-and-enumerate-all-tables-linked-to-external-data-sources.cs new file mode 100644 index 0000000000..8de6b7e109 --- /dev/null +++ b/working-with-tables/load-an-existing-excel-workbook-containing-query-tables-and-enumerate-all-tables-linked-to-external-data-sources.cs @@ -0,0 +1,112 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +namespace AsposeCellsExamples +{ + public class EnumerateExternalQueryTables + { + public static void Main(string[] args) + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + + public static void Run() + { + // Path to the input workbook + string inputPath = "InputWorkbookWithQueryTables.xlsx"; + + // Verify that the file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the existing workbook that contains query tables + Workbook workbook; + try + { + workbook = new Workbook(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load workbook: {ex.Message}"); + return; + } + + // Iterate through each worksheet in the workbook + for (int wsIndex = 0; wsIndex < workbook.Worksheets.Count; wsIndex++) + { + Worksheet sheet = workbook.Worksheets[wsIndex]; + Console.WriteLine($"Worksheet: {sheet.Name}"); + + // Check if the worksheet has any query tables + if (sheet.QueryTables.Count == 0) + { + Console.WriteLine(" No query tables in this worksheet."); + continue; + } + + // Enumerate each query table + for (int qtIndex = 0; qtIndex < sheet.QueryTables.Count; qtIndex++) + { + QueryTable queryTable = sheet.QueryTables[qtIndex]; + Console.WriteLine($" Query Table {qtIndex + 1}: {queryTable.Name}"); + Console.WriteLine($" Result Range: {queryTable.ResultRange.Address}"); + + // Get the external connection associated with the query table + ExternalConnection extConn = queryTable.ExternalConnection; + if (extConn != null) + { + Console.WriteLine(" Linked to external data source:"); + Console.WriteLine($" Connection ID : {extConn.Id}"); + Console.WriteLine($" Connection Name : {extConn.Name}"); + Console.WriteLine($" Connection Type : {extConn.ClassType}"); + Console.WriteLine($" Connection String: {extConn.ConnectionString}"); + Console.WriteLine($" Refresh on Load : {extConn.RefreshOnLoad}"); + } + else + { + Console.WriteLine(" No external connection associated with this query table."); + } + } + } + + // List workbook‑level external links (if any) + ExternalLinkCollection externalLinks = workbook.Worksheets.ExternalLinks; + if (externalLinks.Count > 0) + { + Console.WriteLine("\nWorkbook External Links:"); + for (int i = 0; i < externalLinks.Count; i++) + { + ExternalLink link = externalLinks[i]; + Console.WriteLine($" Link {i + 1}: DataSource = {link.DataSource}"); + } + } + else + { + Console.WriteLine("\nNo workbook external links found."); + } + + // Save the workbook (unchanged) if needed + try + { + workbook.Save("EnumeratedQueryTablesOutput.xlsx"); + Console.WriteLine("\nWorkbook saved as EnumeratedQueryTablesOutput.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to save workbook: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/lock-specific-columns-in-the-table-to-prevent-accidental-modification-while-allowing-other-columns-to-edit.cs b/working-with-tables/lock-specific-columns-in-the-table-to-prevent-accidental-modification-while-allowing-other-columns-to-edit.cs new file mode 100644 index 0000000000..ad64c8053c --- /dev/null +++ b/working-with-tables/lock-specific-columns-in-the-table-to-prevent-accidental-modification-while-allowing-other-columns-to-edit.cs @@ -0,0 +1,58 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + public class LockColumnsDemo + { + public static void Main() + { + try + { + Run(); + Console.WriteLine("Workbook saved successfully."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Prepare a StyleFlag indicating the Locked attribute should be applied + StyleFlag flag = new StyleFlag { Locked = true }; + + // Unlock all columns first (so only selected columns will be locked later) + for (int col = 0; col <= worksheet.Cells.MaxColumn; col++) + { + Style style = worksheet.Cells.Columns[col].GetStyle(); + style.IsLocked = false; + worksheet.Cells.Columns[col].ApplyStyle(style, flag); + } + + // Columns to lock (e.g., column A and C) – 0‑based indexes + int[] columnsToLock = { 0, 2 }; + + foreach (int colIndex in columnsToLock) + { + Style style = worksheet.Cells.Columns[colIndex].GetStyle(); + style.IsLocked = true; + worksheet.Cells.Columns[colIndex].ApplyStyle(style, flag); + } + + // Protect the worksheet so that the locking takes effect + worksheet.Protect(ProtectionType.All); + // Allow selecting unlocked cells while preventing edits on locked ones + worksheet.Protection.AllowSelectingUnlockedCell = true; + + // Save the workbook + string outputPath = "LockedColumnsDemo.xlsx"; + workbook.Save(outputPath, SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/overwrite-an-existing-value-in-a-table-cell-using-cellputvalue-after-retrieving-the-table-with-cellgettable.cs b/working-with-tables/overwrite-an-existing-value-in-a-table-cell-using-cellputvalue-after-retrieving-the-table-with-cellgettable.cs new file mode 100644 index 0000000000..84d497180f --- /dev/null +++ b/working-with-tables/overwrite-an-existing-value-in-a-table-cell-using-cellputvalue-after-retrieving-the-table-with-cellgettable.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class OverwriteTableCell +{ + 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 that will become a table (range A1:C3) + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + cells["C1"].PutValue("Score"); + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["C2"].PutValue(85); + cells["A3"].PutValue(2); + cells["B3"].PutValue("Bob"); + cells["C3"].PutValue(90); + + // Create a ListObject (table) covering the populated range + int tableIndex = sheet.ListObjects.Add(0, 0, 2, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Select a cell inside the table that we want to overwrite (C2) + Cell targetCell = cells["C2"]; // Current value is 85 + + // Retrieve the table that contains this cell using Cell.GetTable() + ListObject parentTable = targetCell.GetTable(); + + // Ensure the cell belongs to the expected table before overwriting + if (parentTable != null && parentTable == table) + { + // Overwrite the existing value using Cell.PutValue + targetCell.PutValue(95); // New score value + } + + // Save the workbook + workbook.Save("OverwriteTableCell.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/working-with-tables/programmatically-change-the-tables-style-to-tablestylelight10-to-match-the-workbooks-color-palette.cs b/working-with-tables/programmatically-change-the-tables-style-to-tablestylelight10-to-match-the-workbooks-color-palette.cs new file mode 100644 index 0000000000..9f3592fbb3 --- /dev/null +++ b/working-with-tables/programmatically-change-the-tables-style-to-tablestylelight10-to-match-the-workbooks-color-palette.cs @@ -0,0 +1,30 @@ +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Add sample data for the table + sheet.Cells["A1"].PutValue("Name"); + sheet.Cells["B1"].PutValue("Age"); + sheet.Cells["A2"].PutValue("John"); + sheet.Cells["B2"].PutValue(30); + sheet.Cells["A3"].PutValue("Jane"); + sheet.Cells["B3"].PutValue(25); + + // Create a ListObject (table) that includes the data range + int tableIdx = sheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = sheet.ListObjects[tableIdx]; + + // Apply the built‑in style 'TableStyleLight10' to the table + table.TableStyleType = TableStyleType.TableStyleLight10; + + // Save the workbook + workbook.Save("TableStyleLight10.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/programmatically-copy-a-tables-style-to-another-table-to-ensure-consistent-visual-formatting-across-sheets.cs b/working-with-tables/programmatically-copy-a-tables-style-to-another-table-to-ensure-consistent-visual-formatting-across-sheets.cs new file mode 100644 index 0000000000..75a9740000 --- /dev/null +++ b/working-with-tables/programmatically-copy-a-tables-style-to-another-table-to-ensure-consistent-visual-formatting-across-sheets.cs @@ -0,0 +1,81 @@ +using System; +using System.Drawing; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsDemo +{ + class TableStyleCopyDemo + { + static void Main() + { + try + { + Run(); + Console.WriteLine("Workbook saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + // Create a new workbook and get the first worksheet (source sheet) + Workbook workbook = new Workbook(); + Worksheet sourceSheet = workbook.Worksheets[0]; + sourceSheet.Name = "Source"; + + // Populate source sheet with sample data + sourceSheet.Cells["A1"].PutValue("Product"); + sourceSheet.Cells["B1"].PutValue("Price"); + sourceSheet.Cells["A2"].PutValue("Apple"); + sourceSheet.Cells["B2"].PutValue(1.2); + sourceSheet.Cells["A3"].PutValue("Banana"); + sourceSheet.Cells["B3"].PutValue(0.8); + + // Add a table to the source sheet + int srcTableIndex = sourceSheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject srcTable = sourceSheet.ListObjects[srcTableIndex]; + srcTable.ShowTableStyleFirstColumn = true; + srcTable.ShowTableStyleLastColumn = true; + + // Apply a built‑in table style to the source table + // (Custom table styles require the TableStyles collection which may not be available in all versions) + srcTable.TableStyleName = "TableStyleMedium2"; + + // Add a second worksheet (destination sheet) and populate it with similar data + Worksheet destSheet = workbook.Worksheets[workbook.Worksheets.Add()]; + destSheet.Name = "Destination"; + + destSheet.Cells["A1"].PutValue("Product"); + destSheet.Cells["B1"].PutValue("Price"); + destSheet.Cells["A2"].PutValue("Orange"); + destSheet.Cells["B2"].PutValue(1.5); + destSheet.Cells["A3"].PutValue("Grape"); + destSheet.Cells["B3"].PutValue(2.0); + + // Add a table to the destination sheet + int destTableIndex = destSheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject destTable = destSheet.ListObjects[destTableIndex]; + destTable.ShowTableStyleFirstColumn = true; + destTable.ShowTableStyleLastColumn = true; + + // Copy the style from the source table to the destination table + destTable.TableStyleName = srcTable.TableStyleName; + + // Save the workbook + string outputPath = "TableStyleCopied.xlsx"; + try + { + workbook.Save(outputPath); + } + catch (Exception saveEx) + { + Console.WriteLine($"Failed to save workbook: {saveEx.Message}"); + throw; + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/programmatically-detect-tables-lacking-a-header-row-and-add-a-default-header-with-generic-column-names.cs b/working-with-tables/programmatically-detect-tables-lacking-a-header-row-and-add-a-default-header-with-generic-column-names.cs new file mode 100644 index 0000000000..8daaebcc87 --- /dev/null +++ b/working-with-tables/programmatically-detect-tables-lacking-a-header-row-and-add-a-default-header-with-generic-column-names.cs @@ -0,0 +1,60 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTableHeaderFix +{ + class Program + { + static void Main(string[] args) + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data without a header row + // Table will occupy A1:C3 (3 rows, 3 columns) with no header row + worksheet.Cells["A1"].PutValue("Apple"); + worksheet.Cells["B1"].PutValue(10); + worksheet.Cells["C1"].PutValue(1.5); + worksheet.Cells["A2"].PutValue("Banana"); + worksheet.Cells["B2"].PutValue(20); + worksheet.Cells["C2"].PutValue(2.0); + worksheet.Cells["A3"].PutValue("Cherry"); + worksheet.Cells["B3"].PutValue(30); + worksheet.Cells["C3"].PutValue(2.5); + + // Add a ListObject (table) without headers (hasHeaders = false) + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 2, false); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "FruitTable"; + + // Iterate through all tables in the worksheet + foreach (ListObject lo in worksheet.ListObjects) + { + // Insert a new row at the start of the table to become the header row + worksheet.Cells.InsertRows(lo.StartRow, 1); + + // Fill the new header row with generic column names (Column1, Column2, ...) + int columnCount = lo.ListColumns.Count; + for (int col = 0; col < columnCount; col++) + { + worksheet.Cells[lo.StartRow, lo.StartColumn + col].PutValue($"Column{col + 1}"); + } + + // Update the ListObject's column names to match the new header cells + lo.UpdateColumnName(); + } + + // Save the workbook + workbook.Save("TableWithHeaders.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/programmatically-detect-tables-that-lack-a-totals-row-and-add-one-with-default-sum-calculations.cs b/working-with-tables/programmatically-detect-tables-that-lack-a-totals-row-and-add-one-with-default-sum-calculations.cs new file mode 100644 index 0000000000..9969796916 --- /dev/null +++ b/working-with-tables/programmatically-detect-tables-that-lack-a-totals-row-and-add-one-with-default-sum-calculations.cs @@ -0,0 +1,67 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTotalsRowDemo +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data (header + 5 rows, 3 columns) + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["C1"].PutValue("Price"); + + for (int i = 2; i <= 6; i++) + { + cells[$"A{i}"].PutValue($"Product {i - 1}"); + cells[$"B{i}"].PutValue(i * 10); // numeric column + cells[$"C{i}"].PutValue(i * 2.5); // numeric column + } + + // Add a table that covers the data range + int tableIndex = sheet.ListObjects.Add("A1", "C6", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // ----------------------------------------------------------------- + // Detect tables without a totals row and add one with default sums + // ----------------------------------------------------------------- + foreach (ListObject lo in sheet.ListObjects) + { + // If the table already shows a totals row, skip it + if (lo.ShowTotals) + continue; + + // Enable the totals row + lo.ShowTotals = true; + + // Set each column's TotalsCalculation to Sum (default for numeric data) + // For the first column (usually a label), set a friendly label instead + for (int col = 0; col < lo.ListColumns.Count; col++) + { + ListColumn lc = lo.ListColumns[col]; + if (col == 0) + { + // First column: display a label like "Total" + lc.TotalsRowLabel = "Grand Total"; + lc.TotalsCalculation = TotalsCalculation.None; + } + else + { + // Other columns: sum the values + lc.TotalsCalculation = TotalsCalculation.Sum; + } + } + } + + // Save the workbook + workbook.Save("WorkbookWithTotalsRows.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/programmatically-retrieve-the-address-range-of-a-table-and-use-it-as-a-named-range-for-formulas.cs b/working-with-tables/programmatically-retrieve-the-address-range-of-a-table-and-use-it-as-a-named-range-for-formulas.cs new file mode 100644 index 0000000000..09f19325d2 --- /dev/null +++ b/working-with-tables/programmatically-retrieve-the-address-range-of-a-table-and-use-it-as-a-named-range-for-formulas.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsTableToNamedRange +{ + class Program + { + static void Main() + { + try + { + // 1. Create a new workbook (lifecycle rule: create) + Workbook workbook = new Workbook(); + + // 2. Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + sheet.Name = "DataSheet"; + + // 3. Populate sample data that will become a table + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Quantity"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue(20); + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue(30); + + // 4. Add a ListObject (Excel Table) covering the data range A1:B4 + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = sheet.ListObjects.Add(0, 0, 3, 1, true); + Aspose.Cells.Tables.ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "SalesTable"; + + // 5. Retrieve the data range of the table using the DataRange property + Aspose.Cells.Range tableDataRange = table.DataRange; // e.g., A2:B4 (excluding header) + + // 6. Build the full address string for the named range (including sheet name) + string namedRangeRef = $"={sheet.Name}!{tableDataRange.Address}"; + + // 7. Create a named range that points to the table's data range + int nameIdx = workbook.Worksheets.Names.Add("SalesData"); + Name namedRange = workbook.Worksheets.Names[nameIdx]; + namedRange.RefersTo = namedRangeRef; // e.g., =DataSheet!A2:B4 + + // 8. Use the named range in a formula (sum of Quantity column) + // Since the table has two columns, column B holds Quantity. + // We'll sum the entire named range; Excel will sum numeric cells only. + sheet.Cells["D1"].Formula = "=SUM(SalesData)"; + + // 9. Calculate formulas to obtain the result + workbook.CalculateFormula(); + + // 10. Output the result to console (optional verification) + Console.WriteLine($"Named range 'SalesData' refers to: {namedRange.RefersTo}"); + Console.WriteLine($"Sum of SalesData (Quantity): {sheet.Cells["D1"].Value}"); + + // 11. Save the workbook (lifecycle rule: save) + string outputPath = "TableToNamedRange.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'"); + } + catch (Exception ex) + { + // Runtime safety: report any unexpected errors + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/protect-the-entire-table-with-a-password-allowing-only-readonly-access-for-external-users.cs b/working-with-tables/protect-the-entire-table-with-a-password-allowing-only-readonly-access-for-external-users.cs new file mode 100644 index 0000000000..9099669b35 --- /dev/null +++ b/working-with-tables/protect-the-entire-table-with-a-password-allowing-only-readonly-access-for-external-users.cs @@ -0,0 +1,42 @@ +using Aspose.Cells; + +class ProtectTableDemo +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // (Optional) Populate some data in the worksheet + worksheet.Cells["A1"].PutValue("Header1"); + worksheet.Cells["B1"].PutValue("Header2"); + worksheet.Cells["A2"].PutValue("Data1"); + worksheet.Cells["B2"].PutValue("Data2"); + + // Configure worksheet protection to allow only read‑only access + Protection protection = worksheet.Protection; + protection.AllowEditingContent = false; // Disallow editing cell contents + protection.AllowEditingObject = false; // Disallow editing objects + protection.AllowEditingScenario = false; // Disallow editing scenarios + protection.AllowFormattingCell = false; // Disallow formatting cells + protection.AllowFormattingColumn = false; // Disallow formatting columns + protection.AllowFormattingRow = false; // Disallow formatting rows + protection.AllowInsertingColumn = false; // Disallow inserting columns + protection.AllowInsertingRow = false; // Disallow inserting rows + protection.AllowInsertingHyperlink = false; // Disallow inserting hyperlinks + protection.AllowDeletingColumn = false; // Disallow deleting columns + protection.AllowDeletingRow = false; // Disallow deleting rows + protection.AllowSorting = false; // Disallow sorting + protection.AllowFiltering = false; // Disallow filtering + protection.AllowUsingPivotTable = false; // Disallow using pivot tables + protection.AllowSelectingLockedCell = true; // Allow selecting locked cells (read‑only) + protection.AllowSelectingUnlockedCell = true; // Allow selecting unlocked cells + + // Set a password so that only users with the password can unprotect the sheet + protection.Password = "ReadOnlyPwd"; + + // Save the workbook + workbook.Save("ReadOnlyProtectedTable.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/read-the-metadata-of-a-query-table-including-connection-string-command-type-and-refresh-interval.cs b/working-with-tables/read-the-metadata-of-a-query-table-including-connection-string-command-type-and-refresh-interval.cs new file mode 100644 index 0000000000..42cf3b7ec6 --- /dev/null +++ b/working-with-tables/read-the-metadata-of-a-query-table-including-connection-string-command-type-and-refresh-interval.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +class ReadQueryTableMetadata +{ + static void Main() + { + // Load an existing workbook that contains query tables + Workbook workbook = new Workbook("input.xlsx"); + + // Iterate through all worksheets in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + // Skip worksheets without query tables + if (sheet.QueryTables.Count == 0) + continue; + + Console.WriteLine($"Worksheet: {sheet.Name}"); + + // Process each query table in the worksheet + for (int i = 0; i < sheet.QueryTables.Count; i++) + { + QueryTable queryTable = sheet.QueryTables[i]; + Console.WriteLine($" QueryTable {i + 1} Name: {queryTable.Name}"); + + // Retrieve the external connection associated with the query table + ExternalConnection externalConnection = queryTable.ExternalConnection; + + if (externalConnection != null) + { + // Connection string used to connect to the external data source + Console.WriteLine($" Connection String: {externalConnection.ConnectionString}"); + + // Command type (e.g., Text, StoredProcedure, Table, etc.) + Console.WriteLine($" Command Type: {externalConnection.CommandType}"); + + // Refresh interval in minutes (how often the data is refreshed automatically) + Console.WriteLine($" Refresh Interval (minutes): {externalConnection.RefreshInternal}"); + } + else + { + Console.WriteLine(" No external connection associated with this query table."); + } + } + } + + // Optionally save the workbook after reading (no modifications made here) + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/refresh-a-query-table-after-modifying-its-underlying-sql-command-to-reflect-updated-query-results.cs b/working-with-tables/refresh-a-query-table-after-modifying-its-underlying-sql-command-to-reflect-updated-query-results.cs new file mode 100644 index 0000000000..c6f0878b23 --- /dev/null +++ b/working-with-tables/refresh-a-query-table-after-modifying-its-underlying-sql-command-to-reflect-updated-query-results.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +namespace AsposeCellsQueryTableRefreshDemo +{ + 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 \"{inputPath}\" not found."); + return; + } + + // Load the workbook that contains a query table + Workbook workbook = new Workbook(inputPath); + Worksheet worksheet = workbook.Worksheets[0]; + + // Ensure there is at least one query table + if (worksheet.QueryTables.Count == 0) + { + Console.WriteLine("No query tables found in the worksheet."); + return; + } + + // Get the first query table + QueryTable queryTable = worksheet.QueryTables[0]; + + // Access the external connection linked to the query table + ExternalConnection extConn = queryTable.ExternalConnection; + if (extConn is DBConnection dbConn) + { + // Modify the underlying SQL command + dbConn.Command = "SELECT Id, Name, Price FROM Products WHERE Price > 100"; + + // Refresh the query table – Aspose.Cells versions prior to 23.x do not expose a Refresh method. + // If the Refresh method is available in your version, uncomment the line below: + // queryTable.Refresh(); + + Console.WriteLine("Query table command updated."); + } + else + { + Console.WriteLine("The query table does not use a DBConnection that can be modified."); + } + + // Save the workbook with the (potentially) updated data + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved as \"{outputPath}\"."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/refresh-all-pivot-tables-that-reference-a-specific-worksheet-table-after-updating-its-underlying-data.cs b/working-with-tables/refresh-all-pivot-tables-that-reference-a-specific-worksheet-table-after-updating-its-underlying-data.cs new file mode 100644 index 0000000000..94f4895c43 --- /dev/null +++ b/working-with-tables/refresh-all-pivot-tables-that-reference-a-specific-worksheet-table-after-updating-its-underlying-data.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using Aspose.Cells; + +class RefreshPivotTablesDemo +{ + static void Main() + { + const string inputPath = "InputWithPivot.xlsx"; + const string outputPath = "OutputRefreshed.xlsx"; + + try + { + // Verify that the input workbook exists before attempting to load it + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file '{inputPath}' not found."); + return; + } + + // Load the workbook that contains the data table and pivot tables + Workbook workbook = new Workbook(inputPath); + + // Access the worksheet that holds the source table (e.g., named "DataSheet") + Worksheet dataSheet = workbook.Worksheets["DataSheet"]; + if (dataSheet == null) + { + Console.WriteLine("Worksheet 'DataSheet' not found in the workbook."); + return; + } + + // Update the underlying data of the table (example modifications) + dataSheet.Cells["B2"].PutValue(1500); + dataSheet.Cells["B3"].PutValue(2500); + // Add more data updates as needed... + + // Refresh all pivot tables in the workbook so they reflect the changed data + workbook.Worksheets.RefreshPivotTables(); + + // Save the workbook with refreshed pivot tables + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + // Handle any unexpected errors + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/remove-a-tables-totals-row-and-then-readd-it-with-custom-formulas-for-each-numeric-column.cs b/working-with-tables/remove-a-tables-totals-row-and-then-readd-it-with-custom-formulas-for-each-numeric-column.cs new file mode 100644 index 0000000000..654dcb2c15 --- /dev/null +++ b/working-with-tables/remove-a-tables-totals-row-and-then-readd-it-with-custom-formulas-for-each-numeric-column.cs @@ -0,0 +1,70 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // 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 (header + rows) + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["C1"].PutValue("Price"); + + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["C2"].PutValue(2.5); + + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(5); + cells["C3"].PutValue(3.0); + + // Add a table that covers the data range + int tableIndex = worksheet.ListObjects.Add("A1", "C3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Initially show the totals row (optional, just to have one) + table.ShowTotals = true; + + // ----- Remove the existing totals row ----- + table.ShowTotals = false; // hides/removes the totals row + + // ----- Re‑add the totals row with custom formulas ----- + table.ShowTotals = true; // shows a new totals row + + // Iterate through each column of the table + foreach (ListColumn column in table.ListColumns) + { + // The first data cell of the column (row index 1 because row 0 is the header) + Cell firstDataCell = column.Range[1, 0]; + + // If the first data cell contains a numeric value, treat the column as numeric + if (firstDataCell != null && firstDataCell.Type == CellValueType.IsNumeric) + { + // Use a custom totals calculation + column.TotalsCalculation = TotalsCalculation.Custom; + + // Example custom formula: sum of the column values + string customFormula = $"=SUM([{column.Name}])"; + + // Set the custom formula for the totals row of this column + // Parameters: formula string, isR1C1 = false, isLocal = false + column.SetCustomTotalsRowFormula(customFormula, false, false); + } + else + { + // For non‑numeric columns, you can set a label or leave it empty + column.TotalsCalculation = TotalsCalculation.None; + column.TotalsRowLabel = "Total"; + } + } + + // Save the workbook with the updated table totals + workbook.Save("TableWithCustomTotals.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/remove-all-slicers-associated-with-a-specific-table-to-simplify-the-worksheet-interface.cs b/working-with-tables/remove-all-slicers-associated-with-a-specific-table-to-simplify-the-worksheet-interface.cs new file mode 100644 index 0000000000..f10232c46e --- /dev/null +++ b/working-with-tables/remove-all-slicers-associated-with-a-specific-table-to-simplify-the-worksheet-interface.cs @@ -0,0 +1,44 @@ +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Tables; + +class RemoveTableSlicers +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate some 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 a table (ListObject) that covers the data range + int tableIdx = sheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = sheet.ListObjects[tableIdx]; + + // Add a couple of slicers that are linked to the table + SlicerCollection slicers = sheet.Slicers; + slicers.Add(table, table.ListColumns[0], "D1"); // slicer for first column + slicers.Add(table, table.ListColumns[1], "D5"); // slicer for second column + + // ------------------------------------------------------------ + // Remove all slicers that belong to the specified table. + // In this example we know that the worksheet contains only + // slicers for this table, so we can clear the entire collection. + // If other slicers existed, you could iterate the collection and + // remove only those whose SlicerCache is linked to the table. + // ------------------------------------------------------------ + slicers.Clear(); + + // Save the modified workbook + workbook.Save("WorkbookWithoutTableSlicers.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/remove-an-existing-slicer-from-a-table-and-clean-up-associated-connections.cs b/working-with-tables/remove-an-existing-slicer-from-a-table-and-clean-up-associated-connections.cs new file mode 100644 index 0000000000..05928b0fcf --- /dev/null +++ b/working-with-tables/remove-an-existing-slicer-from-a-table-and-clean-up-associated-connections.cs @@ -0,0 +1,72 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Slicers; +using Aspose.Cells.Pivot; +using Aspose.Cells.Tables; + +namespace AsposeCellsDemo +{ + public class RemoveSlicerDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for a table + 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("A"); + worksheet.Cells["B4"].PutValue(30); + + // Add a table covering the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B4", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Add a pivot table based on the same range + int pivotIndex = worksheet.PivotTables.Add("A1:B4", "D1", "Pivot1"); + PivotTable pivotTable = worksheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Value"); + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Add a slicer linked to the pivot table + int slicerIndex = worksheet.Slicers.Add(pivotTable, "E3", "Category"); + Slicer slicer = worksheet.Slicers[slicerIndex]; + + // ----- Removal logic ----- + // 1. Remove the slicer's connection to the pivot table (if any) + slicer.RemovePivotConnection(pivotTable); + + // 2. Remove the slicer from the worksheet's slicer collection + worksheet.Slicers.Remove(slicer); + // ------------------------- + + // Save the workbook to verify that the slicer has been removed + workbook.Save("RemovedSlicer.xlsx"); + Console.WriteLine("Workbook saved successfully as 'RemovedSlicer.xlsx'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + RemoveSlicerDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/remove-an-unwanted-column-from-a-table-while-preserving-the-data-in-other-columns.cs b/working-with-tables/remove-an-unwanted-column-from-a-table-while-preserving-the-data-in-other-columns.cs new file mode 100644 index 0000000000..e245683269 --- /dev/null +++ b/working-with-tables/remove-an-unwanted-column-from-a-table-while-preserving-the-data-in-other-columns.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class RemoveColumnFromTableDemo + { + public static void Main() + { + try + { + Run(); + Console.WriteLine("Workbook saved successfully."); + } + 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 sheet = workbook.Worksheets[0]; + + // Populate sample data for the table (columns A, B, C) + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Score"); + + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["C2"].PutValue(85); + + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + sheet.Cells["C3"].PutValue(92); + + sheet.Cells["A4"].PutValue(3); + sheet.Cells["B4"].PutValue("Charlie"); + sheet.Cells["C4"].PutValue(78); + + // Add a ListObject (table) that includes the data range A1:C4 + int tableIndex = sheet.ListObjects.Add("A1", "C4", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Delete the unwanted column (e.g., column B, zero‑based index 1) + // This removes the column from the worksheet and the table adjusts automatically. + sheet.Cells.DeleteColumn(1); // Delete column B + + // Define output file path + string outputPath = "TableColumnRemoved.xlsx"; + + // Ensure the directory exists before saving + string directory = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + // Save the modified workbook + workbook.Save(outputPath); + } + } +} \ No newline at end of file diff --git a/working-with-tables/remove-duplicate-rows-from-a-table-based-on-a-composite-key-of-two-columns-using-builtin-method.cs b/working-with-tables/remove-duplicate-rows-from-a-table-based-on-a-composite-key-of-two-columns-using-builtin-method.cs new file mode 100644 index 0000000000..d6eb4f8731 --- /dev/null +++ b/working-with-tables/remove-duplicate-rows-from-a-table-based-on-a-composite-key-of-two-columns-using-builtin-method.cs @@ -0,0 +1,57 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsRemoveDuplicatesExample +{ + 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; + + // Add header row (hasHeaders = true) + cells["A1"].PutValue("ID"); // Column 0 + cells["B1"].PutValue("Name"); // Column 1 + cells["C1"].PutValue("Score"); // Column 2 (extra column not part of key) + + // Add sample data with duplicate rows based on the composite key (ID, Name) + // Row 2 + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["C2"].PutValue(85); + // Row 3 (duplicate of row 2 on ID and Name) + cells["A3"].PutValue(1); + cells["B3"].PutValue("Alice"); + cells["C3"].PutValue(90); + // Row 4 + cells["A4"].PutValue(2); + cells["B4"].PutValue("Bob"); + cells["C4"].PutValue(78); + // Row 5 (duplicate of row 4 on ID and Name) + cells["A5"].PutValue(2); + cells["B5"].PutValue("Bob"); + cells["C5"].PutValue(82); + // Row 6 (unique) + cells["A6"].PutValue(3); + cells["B6"].PutValue("Charlie"); + cells["C6"].PutValue(91); + + // Define the range that contains the data (including header) + int startRow = 0; // Header row index + int startColumn = 0; // First column (ID) + int endRow = 5; // Zero‑based index of last data row (row 6 in Excel) + int endColumn = 2; // Last column (Score) + + // Remove duplicates based on the composite key of columns 0 (ID) and 1 (Name) + // hasHeaders = true indicates that the first row contains column names + // columnOffsets specifies which columns form the key (0‑based offsets from startColumn) + cells.RemoveDuplicates(startRow, startColumn, endRow, endColumn, true, new int[] { 0, 1 }); + + // Save the workbook to verify the result + workbook.Save("RemoveDuplicatesCompositeKey.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/reorder-columns-in-a-table-to-match-a-predefined-layout-required-by-downstream-processing-scripts.cs b/working-with-tables/reorder-columns-in-a-table-to-match-a-predefined-layout-required-by-downstream-processing-scripts.cs new file mode 100644 index 0000000000..4c47a2dcc6 --- /dev/null +++ b/working-with-tables/reorder-columns-in-a-table-to-match-a-predefined-layout-required-by-downstream-processing-scripts.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Needed for ListObject + +namespace AsposeCellsColumnReorderDemo +{ + class Program + { + static void Main() + { + try + { + // Create a workbook and populate it with sample data (including header row) + Workbook workbook = new Workbook(); + Worksheet srcSheet = workbook.Worksheets[0]; + srcSheet.Name = "Source"; + + // Headers: ColA, ColB, ColC, ColD + srcSheet.Cells["A1"].PutValue("ColA"); + srcSheet.Cells["B1"].PutValue("ColB"); + srcSheet.Cells["C1"].PutValue("ColC"); + srcSheet.Cells["D1"].PutValue("ColD"); + + // Sample rows + for (int row = 2; row <= 5; row++) + { + srcSheet.Cells[row - 1, 0].PutValue($"A{row - 1}"); + srcSheet.Cells[row - 1, 1].PutValue($"B{row - 1}"); + srcSheet.Cells[row - 1, 2].PutValue($"C{row - 1}"); + srcSheet.Cells[row - 1, 3].PutValue($"D{row - 1}"); + } + + // Desired column order (0‑based indexes of the source columns) + // Example: reorder to C, A, D, B + int[] desiredOrder = new int[] { 2, 0, 3, 1 }; + + // Add a new worksheet that will hold the reordered columns + Worksheet destSheet = workbook.Worksheets.Add("Reordered"); + + // Copy each column from the source sheet to the destination sheet according to the desired order + for (int destCol = 0; destCol < desiredOrder.Length; destCol++) + { + int srcCol = desiredOrder[destCol]; + destSheet.Cells.CopyColumns(srcSheet.Cells, srcCol, destCol, 1); + } + + // Create a table (ListObject) on the destination sheet covering the data range + int totalRows = srcSheet.Cells.MaxDataRow + 1; // include header row + int totalCols = desiredOrder.Length; + int tableIndex = destSheet.ListObjects.Add(0, 0, totalRows - 1, totalCols - 1, true); + ListObject destTable = destSheet.ListObjects[tableIndex]; + destTable.DisplayName = "ReorderedTable"; + + // Ensure the ListObject column names reflect the header cells after reordering + destTable.UpdateColumnName(); + + // Save the workbook with the reordered columns + string outputPath = "ReorderedColumns.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/working-with-tables/retrieve-a-table-from-a-cell-using-cellgettable-and-insert-a-numeric-value-with-cellputvalue.cs b/working-with-tables/retrieve-a-table-from-a-cell-using-cellgettable-and-insert-a-numeric-value-with-cellputvalue.cs new file mode 100644 index 0000000000..8fb94b7d80 --- /dev/null +++ b/working-with-tables/retrieve-a-table-from-a-cell-using-cellgettable-and-insert-a-numeric-value-with-cellputvalue.cs @@ -0,0 +1,64 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class GetTableAndPutValueDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate some data that will become a table + cells["A1"].PutValue("Product"); + cells["B1"].PutValue("Quantity"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(20); + + // Create a ListObject (table) covering the data range A1:B3 + int tableIndex = worksheet.ListObjects.Add("A1", "B3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Choose a cell that lies inside the table (e.g., B2) + Cell cellInTable = cells["B2"]; + + // Retrieve the table that contains this cell using GetTable() + ListObject retrievedTable = cellInTable.GetTable(); + + // Verify that the table was retrieved + if (retrievedTable != null) + { + // Update a cell inside the table (row offset 1, column offset 1 => B3) + retrievedTable.PutCellValue(1, 1, 999); + + // Put a value into a cell outside the original table + Cell targetCell = cells["C2"]; + targetCell.PutValue(12345); + } + + // Save the workbook to a file + workbook.Save("GetTableAndPutValueDemo.xlsx", SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + GetTableAndPutValueDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/retrieve-a-table-with-cellgettable-and-enumerate-its-rows-to-compute-the-sum-of-a-numeric-column.cs b/working-with-tables/retrieve-a-table-with-cellgettable-and-enumerate-its-rows-to-compute-the-sum-of-a-numeric-column.cs new file mode 100644 index 0000000000..4fd1e0eb6b --- /dev/null +++ b/working-with-tables/retrieve-a-table-with-cellgettable-and-enumerate-its-rows-to-compute-the-sum-of-a-numeric-column.cs @@ -0,0 +1,56 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // 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 with a header and a numeric column + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("Cherry"); + cells["B4"].PutValue(15); + + // Create a table (ListObject) covering the data range A1:B4 + int tableIdx = worksheet.ListObjects.Add("A1", "B4", true); + ListObject table = worksheet.ListObjects[tableIdx]; + + // Retrieve the table using a cell that belongs to it + Cell cellInTable = cells["B2"]; + ListObject retrievedTable = cellInTable.GetTable(); + + // Determine the data rows (skip header) and the column index of the numeric data + int dataStartRow = retrievedTable.StartRow + 1; // first data row after header + int dataEndRow = retrievedTable.EndRow; // last data row + int quantityColumn = retrievedTable.StartColumn + 1; // second column (Quantity) + + // Compute the sum of the numeric column + double sum = 0; + for (int row = dataStartRow; row <= dataEndRow; row++) + { + object value = cells[row, quantityColumn].Value; + if (value is double d) + sum += d; + else if (value is int i) + sum += i; + else if (double.TryParse(Convert.ToString(value), out double parsed)) + sum += parsed; + } + + // Write the computed sum below the table + cells[dataEndRow + 2, quantityColumn].PutValue(sum); + + // Save the workbook + workbook.Save("TableSumResult.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/save-the-workbook-containing-the-converted-range-as-ods-and-confirm-the-file-size-reduction.cs b/working-with-tables/save-the-workbook-containing-the-converted-range-as-ods-and-confirm-the-file-size-reduction.cs new file mode 100644 index 0000000000..dce80c5d4e --- /dev/null +++ b/working-with-tables/save-the-workbook-containing-the-converted-range-as-ods-and-confirm-the-file-size-reduction.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Ods; + +namespace AsposeCellsOdsConversionDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and fill it with sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate a large range to make file size noticeable + for (int row = 0; row < 2000; row++) + { + for (int col = 0; col < 20; col++) + { + sheet.Cells[row, col].PutValue($"R{row + 1}C{col + 1}"); + } + } + + // Define file names for the original XLSX and the ODS output + string xlsxPath = "SampleData.xlsx"; + string odsPath = "SampleData.ods"; + + // Save the workbook as XLSX (default options) + workbook.Save(xlsxPath, SaveFormat.Xlsx); + + // Create ODS save options (using default constructor) + OdsSaveOptions odsOptions = new OdsSaveOptions + { + // Example: set generator type to LibreOffice (optional) + GeneratorType = OdsGeneratorType.LibreOffice + }; + + // Save the same workbook as ODS using the options + workbook.Save(odsPath, odsOptions); + + // Get file sizes + long xlsxSize = new FileInfo(xlsxPath).Length; + long odsSize = new FileInfo(odsPath).Length; + + // Output sizes and reduction percentage + Console.WriteLine($"XLSX size: {xlsxSize} bytes"); + Console.WriteLine($"ODS size: {odsSize} bytes"); + + if (xlsxSize > 0) + { + double reduction = (double)(xlsxSize - odsSize) / xlsxSize * 100; + Console.WriteLine($"File size reduction: {reduction:F2}%"); + } + else + { + Console.WriteLine("Original XLSX file size is zero; cannot compute reduction."); + } + + // Clean up + workbook.Dispose(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-a-custom-column-width-for-a-specific-table-column-to-accommodate-long-text-strings.cs b/working-with-tables/set-a-custom-column-width-for-a-specific-table-column-to-accommodate-long-text-strings.cs new file mode 100644 index 0000000000..ceed2b5a3e --- /dev/null +++ b/working-with-tables/set-a-custom-column-width-for-a-specific-table-column-to-accommodate-long-text-strings.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsColumnWidthDemo +{ + class Program + { + static void Main(string[] args) + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate a column with long text that needs a wider column + cells["B1"].PutValue("Short"); + cells["B2"].PutValue("This is a very long piece of text that will not fit in the default column width"); + cells["B3"].PutValue("Another long text entry to demonstrate custom column width"); + + // Set a custom width for column B (index 1) in character units + // Width must be between 0 and 255 characters + cells.SetColumnWidth(1, 40.0); // 40 characters wide + + // Alternatively, you can set the width via the Column object + // worksheet.Cells.Columns[1].Width = 40.0; + + // Save the workbook (lifecycle: save) + workbook.Save("CustomColumnWidthDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-a-custom-formula-in-the-totals-row-to-calculate-average-of-a-specific-column.cs b/working-with-tables/set-a-custom-formula-in-the-totals-row-to-calculate-average-of-a-specific-column.cs new file mode 100644 index 0000000000..028b867017 --- /dev/null +++ b/working-with-tables/set-a-custom-formula-in-the-totals-row-to-calculate-average-of-a-specific-column.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class SetCustomAverageInTotalsRow + { + public static void Run() + { + 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 (header + numeric values) + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Banana"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("Cherry"); + cells["B4"].PutValue(30); + + // Add a table that includes the data range (A1:B4) and enable the totals row + int tableIndex = worksheet.ListObjects.Add("A1", "B4", true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.ShowTotals = true; + + // The column we want the average for is the second column (Quantity) + ListColumn quantityColumn = table.ListColumns[1]; + + // Set the totals calculation type to Custom + quantityColumn.TotalsCalculation = TotalsCalculation.Custom; + + // Define a custom formula for the totals row using structured reference syntax + quantityColumn.SetCustomTotalsRowFormula("=AVERAGE([Quantity])", false, false); + + // Save the workbook + string outputPath = "CustomAverageTotalsRow.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Application entry point + public class Program + { + public static void Main(string[] args) + { + SetCustomAverageInTotalsRow.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-a-tables-column-to-use-a-custom-date-format-ddmmmyyyy-for-standardized-display-across-reports.cs b/working-with-tables/set-a-tables-column-to-use-a-custom-date-format-ddmmmyyyy-for-standardized-display-across-reports.cs new file mode 100644 index 0000000000..92506d0e89 --- /dev/null +++ b/working-with-tables/set-a-tables-column-to-use-a-custom-date-format-ddmmmyyyy-for-standardized-display-across-reports.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +class SetTableColumnDateFormat +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data with a header and a few dates + worksheet.Cells["A1"].PutValue("Date"); + worksheet.Cells["A2"].PutValue(new DateTime(2023, 1, 15)); + worksheet.Cells["A3"].PutValue(new DateTime(2023, 2, 20)); + worksheet.Cells["A4"].PutValue(new DateTime(2023, 3, 25)); + + // Create a table (ListObject) that includes the header and data + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.DisplayName = "DateTable"; + + // Create a style with the desired custom date format + Style dateStyle = workbook.CreateStyle(); + dateStyle.Custom = "dd-MMM-yyyy"; + + // Apply the style to the entire column of the table (the date column) + int dateColumnIndex = table.StartColumn; // column index of the first (date) column + + // Apply to header cell + worksheet.Cells[table.StartRow, dateColumnIndex].SetStyle(dateStyle); + + // Apply to each data cell in the column + if (table.DataRange != null) + { + int firstRow = table.DataRange.FirstRow; + int lastRow = firstRow + table.DataRange.RowCount - 1; + + for (int row = firstRow; row <= lastRow; row++) + { + worksheet.Cells[row, dateColumnIndex].SetStyle(dateStyle); + } + } + + // Save the workbook (ensure the directory exists) + string outputPath = "TableDateFormat.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/working-with-tables/set-tabletorangeoptionslastrow-to-zero-to-remove-all-formatting-during-the-table-to-range-conversion.cs b/working-with-tables/set-tabletorangeoptionslastrow-to-zero-to-remove-all-formatting-during-the-table-to-range-conversion.cs new file mode 100644 index 0000000000..35187ad31b --- /dev/null +++ b/working-with-tables/set-tabletorangeoptionslastrow-to-zero-to-remove-all-formatting-during-the-table-to-range-conversion.cs @@ -0,0 +1,67 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class TableToRangeRemoveFormatting + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate the worksheet with sample data (5 columns, 10 rows) + for (int col = 0; col < 5; col++) + { + cells[0, col].PutValue($"Header {col + 1}"); + } + for (int row = 1; row < 10; row++) + { + for (int col = 0; col < 5; col++) + { + cells[row, col].PutValue(row * (col + 1)); + } + } + + // Add a ListObject (table) covering the populated range + int tableIndex = worksheet.ListObjects.Add(0, 0, 9, 4, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Optionally set a table style (formatting will be removed after conversion) + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Create TableToRangeOptions and set LastRow to zero (removes formatting) + TableToRangeOptions options = new TableToRangeOptions + { + LastRow = 0 + }; + + // Convert the table to a normal range using the options + table.ConvertToRange(options); + + // Save the workbook to verify the result + string outputPath = "TableToRange_NoFormatting.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + TableToRangeRemoveFormatting.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-background-refresh-property-of-a-query-table-to-false-ensuring-synchronous-data-retrieval.cs b/working-with-tables/set-the-background-refresh-property-of-a-query-table-to-false-ensuring-synchronous-data-retrieval.cs new file mode 100644 index 0000000000..5db35ebb8e --- /dev/null +++ b/working-with-tables/set-the-background-refresh-property-of-a-query-table-to-false-ensuring-synchronous-data-retrieval.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +namespace AsposeCellsExamples +{ + public class SetQueryTableBackgroundRefresh + { + public static void Run() + { + try + { + // Create a new workbook (or load an existing one if needed) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Ensure there is at least one query table in the worksheet + if (worksheet.QueryTables.Count > 0) + { + // Get the first query table + QueryTable queryTable = worksheet.QueryTables[0]; + + // Retrieve the associated external connection (read‑only property) + ExternalConnection externalConnection = queryTable.ExternalConnection; + + if (externalConnection != null) + { + // Set BackgroundRefresh to false for synchronous data retrieval + externalConnection.BackgroundRefresh = false; + Console.WriteLine("BackgroundRefresh set to: " + externalConnection.BackgroundRefresh); + } + else + { + Console.WriteLine("The query table does not have an associated external connection."); + } + } + else + { + Console.WriteLine("No query tables found in the worksheet."); + } + + // Save the workbook with the modified settings + string outputPath = "QueryTableBackgroundRefreshDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine("Workbook saved to " + Path.GetFullPath(outputPath)); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + SetQueryTableBackgroundRefresh.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-list-object-to-display-a-totals-row-and-configure-count-aggregation-for-a-text-column.cs b/working-with-tables/set-the-list-object-to-display-a-totals-row-and-configure-count-aggregation-for-a-text-column.cs new file mode 100644 index 0000000000..99e4f823c2 --- /dev/null +++ b/working-with-tables/set-the-list-object-to-display-a-totals-row-and-configure-count-aggregation-for-a-text-column.cs @@ -0,0 +1,59 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace Demo +{ + class ListObjectTotalsCountDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data (text column + numeric column) + worksheet.Cells["A1"].PutValue("Item"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["A4"].PutValue("Apple"); + worksheet.Cells["B4"].PutValue(15); + + // Add a ListObject (table) that includes the data range + int tableIndex = worksheet.ListObjects.Add("A1", "B4", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Enable the totals row + table.ShowTotals = true; + + // Set count aggregation for the text column (first column) + table.ListColumns[0].TotalsCalculation = TotalsCalculation.Count; + + // Optional: set a label for the totals row of that column + table.ListColumns[0].TotalsRowLabel = "Count"; + + // Save the workbook + string outputPath = "ListObjectTotalsCountDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + class Program + { + static void Main(string[] args) + { + ListObjectTotalsCountDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-query-tables-connection-string-to-use-integrated-security-for-secure-access-to-the-database.cs b/working-with-tables/set-the-query-tables-connection-string-to-use-integrated-security-for-secure-access-to-the-database.cs new file mode 100644 index 0000000000..8a7f024232 --- /dev/null +++ b/working-with-tables/set-the-query-tables-connection-string-to-use-integrated-security-for-secure-access-to-the-database.cs @@ -0,0 +1,42 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +class Program +{ + static void Main() + { + // Load a workbook that already contains a query table. + Workbook workbook = new Workbook("input.xlsx"); + + // Access the first worksheet (adjust index if needed). + Worksheet sheet = workbook.Worksheets[0]; + + // Verify that the worksheet has at least one query table. + if (sheet.QueryTables.Count > 0) + { + // Retrieve the first query table. + QueryTable queryTable = sheet.QueryTables[0]; + + // Obtain the connection id associated with the query table. + int connectionId = queryTable.ConnectionId; + + // Get the external connection object from the workbook's collection. + ExternalConnection externalConn = workbook.DataConnections[connectionId] as ExternalConnection; + + // Ensure the connection is a DBConnection (OLE DB/ODBC). + if (externalConn is DBConnection dbConn) + { + // Set the connection string to use Integrated Security (Windows authentication). + dbConn.ConnectionString = "Provider=SQLOLEDB;Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI;"; + + // Optionally specify the command and its type. + dbConn.CommandType = OLEDBCommandType.SqlStatement; + dbConn.Command = "SELECT * FROM MyTable"; + } + } + + // Save the workbook with the updated connection string. + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-header-row-option-to-false-for-a-compact-layout-in-a-dashboard-view.cs b/working-with-tables/set-the-tables-show-header-row-option-to-false-for-a-compact-layout-in-a-dashboard-view.cs new file mode 100644 index 0000000000..cb6e1a21aa --- /dev/null +++ b/working-with-tables/set-the-tables-show-header-row-option-to-false-for-a-compact-layout-in-a-dashboard-view.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsDashboardDemo +{ + public class TableHeaderVisibility + { + public static void Run() + { + try + { + // 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("Product"); + worksheet.Cells["B1"].PutValue("Quantity"); + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(120); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(85); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(60); + + // Add a ListObject (Excel table) covering the data range + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 3, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Apply a built‑in table style (optional, for visual compactness) + table.TableStyleType = TableStyleType.TableStyleMedium2; + + // Hide the header row as required for the compact dashboard layout + table.ShowHeaderRow = false; + + // Define output path + string outputPath = "DashboardCompactTable.xlsx"; + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + TableHeaderVisibility.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-header-row-option-to-true-and-apply-a-bold-font-style-to-header-cells.cs b/working-with-tables/set-the-tables-show-header-row-option-to-true-and-apply-a-bold-font-style-to-header-cells.cs new file mode 100644 index 0000000000..3ffe567996 --- /dev/null +++ b/working-with-tables/set-the-tables-show-header-row-option-to-true-and-apply-a-bold-font-style-to-header-cells.cs @@ -0,0 +1,65 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class TableHeaderBoldDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate header row + worksheet.Cells["A1"].PutValue("Product"); + worksheet.Cells["B1"].PutValue("Price"); + + // Populate some data rows + worksheet.Cells["A2"].PutValue("Apple"); + worksheet.Cells["B2"].PutValue(2.5); + worksheet.Cells["A3"].PutValue("Banana"); + worksheet.Cells["B3"].PutValue(1.8); + worksheet.Cells["A4"].PutValue("Cherry"); + worksheet.Cells["B4"].PutValue(3.2); + + // Define the range of the table (including header row) + int firstRow = 0; // zero‑based index for row 1 + int firstColumn = 0; // column A + int lastRow = 4; // row 5 (zero‑based) + int lastColumn = 1; // column B + + // Add a ListObject (table) to the worksheet + int tableIndex = worksheet.ListObjects.Add(firstRow, firstColumn, lastRow, lastColumn, true); + ListObject table = worksheet.ListObjects[tableIndex]; + table.ShowHeaderRow = true; + + // Create a style with bold font for the header row + Style boldStyle = workbook.CreateStyle(); + boldStyle.Font.IsBold = true; + StyleFlag flag = new StyleFlag { FontBold = true }; + worksheet.Cells.ApplyRowStyle(firstRow, boldStyle, flag); + + // Save the workbook + string outputPath = "TableHeaderBoldDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + TableHeaderBoldDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-header-row-option-to-true-and-lock-the-header-cells-to-prevent-editing.cs b/working-with-tables/set-the-tables-show-header-row-option-to-true-and-lock-the-header-cells-to-prevent-editing.cs new file mode 100644 index 0000000000..7f1e057162 --- /dev/null +++ b/working-with-tables/set-the-tables-show-header-row-option-to-true-and-lock-the-header-cells-to-prevent-editing.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Add header values and some sample data + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Price"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(2.5); + sheet.Cells["A3"].PutValue("Banana"); + sheet.Cells["B3"].PutValue(1.8); + + // Create a table (ListObject) that includes the header row + // Parameters: first row, first column, last row, last column, hasHeaders + int tableIndex = sheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Ensure the header row is visible + table.ShowHeaderRow = true; + + // Lock the header cells so they cannot be edited + for (int col = table.StartColumn; col <= table.EndColumn; col++) + { + Cell headerCell = sheet.Cells[table.StartRow, col]; + Style style = headerCell.GetStyle(); + style.IsLocked = true; // Mark cell as locked + headerCell.SetStyle(style); // Apply the style back to the cell + } + + // Protect the worksheet to enforce the locked cells + sheet.Protect(ProtectionType.All); + + // Define output file path + string outputPath = "TableHeaderLocked.xlsx"; + + // Save the workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-calculates-median-value.cs b/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-calculates-median-value.cs new file mode 100644 index 0000000000..be6312ffee --- /dev/null +++ b/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-calculates-median-value.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class TableTotalsMedianDemo + { + public static void Run() + { + 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 (header + numeric values) + cells["A1"].PutValue("Item"); + cells["B1"].PutValue("Quantity"); + cells["A2"].PutValue("Apple"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("Orange"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("Banana"); + cells["B4"].PutValue(30); + cells["A5"].PutValue("Grape"); + cells["B5"].PutValue(40); + + // Add a table that includes the data range (A1:B5) + int tableIndex = worksheet.ListObjects.Add("A1", "B5", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Show the totals row for the table + table.ShowTotals = true; + + // Configure the second column (Quantity) to use a custom totals calculation + ListColumn quantityColumn = table.ListColumns[1]; // zero‑based index + quantityColumn.TotalsCalculation = TotalsCalculation.Custom; + + // Set a custom formula that calculates the median of the Quantity column + // The formula uses structured table reference syntax: =MEDIAN([Quantity]) + quantityColumn.SetCustomTotalsRowFormula("=MEDIAN([Quantity])", false, false); + + // Optionally, set a label for the totals row in the first column + table.ListColumns[0].TotalsRowLabel = "Median"; + + // Save the workbook + string outputPath = "TableTotalsMedianDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + TableTotalsMedianDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-counts-distinct-values.cs b/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-counts-distinct-values.cs new file mode 100644 index 0000000000..3fd79713a9 --- /dev/null +++ b/working-with-tables/set-the-tables-show-totals-row-option-and-configure-a-custom-formula-that-counts-distinct-values.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsTotalsRowDemo +{ + class Program + { + static void Main(string[] args) + { + 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 with a header and some duplicate values + cells["A1"].PutValue("Category"); // Header + cells["A2"].PutValue("Apple"); + cells["A3"].PutValue("Banana"); + cells["A4"].PutValue("Apple"); + cells["A5"].PutValue("Orange"); + cells["A6"].PutValue("Banana"); + + // Add a table that includes the data range (A1:A6) and has a header row + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 5, 0, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Enable the totals row for the table + table.ShowTotals = true; + + // Configure the first column (Category) to use a custom totals calculation + ListColumn categoryColumn = table.ListColumns[0]; + categoryColumn.TotalsCalculation = TotalsCalculation.Custom; + + // Set a custom formula that counts distinct values in the column. + // The formula uses COUNTIF to count each occurrence and then sums the reciprocals. + // This is an array‑style formula; Aspose.Cells accepts it as a regular formula string. + string distinctCountFormula = "=SUM(1/COUNTIF([Category],[Category]))"; + // isR1C1 = false (A1 style), isLocal = false (invariant) + categoryColumn.SetCustomTotalsRowFormula(distinctCountFormula, false, false); + + // Optionally set a label for the totals row in the second column (if it exists) + // Here we add a second column just to demonstrate the label. + cells["B1"].PutValue("Value"); + cells["B2"].PutValue(10); + cells["B3"].PutValue(20); + cells["B4"].PutValue(30); + cells["B5"].PutValue(40); + cells["B6"].PutValue(50); + + // Expand the table to include the second column (hasHeaders = true) + table.Resize(0, 0, 5, 1, true); + + // Set a label for the totals row of the second column + table.ListColumns[1].TotalsRowLabel = "Distinct Count"; + + // Save the workbook + string outputPath = "TableWithDistinctCountTotals.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/set-the-tables-show-totals-row-option-to-false-removing-the-totals-row-from-the-display.cs b/working-with-tables/set-the-tables-show-totals-row-option-to-false-removing-the-totals-row-from-the-display.cs new file mode 100644 index 0000000000..75338d5832 --- /dev/null +++ b/working-with-tables/set-the-tables-show-totals-row-option-to-false-removing-the-totals-row-from-the-display.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class SetTableShowTotalsFalse +{ + 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 + sheet.Cells["A1"].PutValue("Product"); + sheet.Cells["B1"].PutValue("Price"); + sheet.Cells["A2"].PutValue("Apple"); + sheet.Cells["B2"].PutValue(10); + sheet.Cells["A3"].PutValue("Orange"); + sheet.Cells["B3"].PutValue(15); + sheet.Cells["A4"].PutValue("Banana"); + sheet.Cells["B4"].PutValue(8); + + // Create a ListObject (table) that includes the data range + int tableIndex = sheet.ListObjects.Add("A1", "B4", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // (Optional) Show the totals row first to demonstrate the change + table.ShowTotals = true; + + // Hide the totals row by setting ShowTotals to false + table.ShowTotals = false; + + // Save the workbook to a file + workbook.Save("TableWithoutTotals.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/sort-the-table-by-two-columns-first-ascending-by-date-then-descending-by-amount.cs b/working-with-tables/sort-the-table-by-two-columns-first-ascending-by-date-then-descending-by-amount.cs new file mode 100644 index 0000000000..d64e14e342 --- /dev/null +++ b/working-with-tables/sort-the-table-by-two-columns-first-ascending-by-date-then-descending-by-amount.cs @@ -0,0 +1,44 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Load the workbook that contains the table to be sorted. + // Replace "input.xlsx" with the actual file path. + Workbook workbook = new Workbook("input.xlsx"); + Worksheet worksheet = workbook.Worksheets[0]; + + // Configure the DataSorter. + // Assume the first row contains headers. + // Column A (index 0) holds the Date values. + // Column B (index 1) holds the Amount values. + DataSorter sorter = workbook.DataSorter; + sorter.HasHeaders = true; + + // First key: Date column, ascending order. + sorter.Key1 = 0; // Date column (A) + sorter.Order1 = SortOrder.Ascending; + + // Second key: Amount column, descending order. + sorter.Key2 = 1; // Amount column (B) + sorter.Order2 = SortOrder.Descending; + + // Define the area to sort (including headers and all data rows/columns). + CellArea sortArea = new CellArea + { + StartRow = 0, + StartColumn = 0, + EndRow = worksheet.Cells.MaxDataRow, + EndColumn = worksheet.Cells.MaxDataColumn + }; + + // Perform the sort. + sorter.Sort(worksheet.Cells, sortArea); + + // Save the sorted workbook. + // Replace "sorted_output.xlsx" with the desired output path. + workbook.Save("sorted_output.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/unprotect-the-previously-secured-table-using-the-correct-password-to-enable-editing-operations.cs b/working-with-tables/unprotect-the-previously-secured-table-using-the-correct-password-to-enable-editing-operations.cs new file mode 100644 index 0000000000..599b9ccdfa --- /dev/null +++ b/working-with-tables/unprotect-the-previously-secured-table-using-the-correct-password-to-enable-editing-operations.cs @@ -0,0 +1,47 @@ +using Aspose.Cells; +using System; +using System.IO; + +class UnprotectWorksheetDemo +{ + static void Main() + { + try + { + const string inputPath = "ProtectedWorkbook.xlsx"; + const string outputPath = "UnprotectedWorkbook.xlsx"; + const string workbookPassword = "password123"; // password for the workbook file + + // Verify that the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook with the required password + LoadOptions loadOptions = new LoadOptions + { + Password = workbookPassword + }; + Workbook workbook = new Workbook(inputPath, loadOptions); + + // Access the first worksheet (index 0) + Worksheet worksheet = workbook.Worksheets[0]; + + // Unprotect the worksheet (same password as used for the workbook) + worksheet.Unprotect(workbookPassword); + + // Confirm that the worksheet is no longer protected + Console.WriteLine("Worksheet is protected: " + worksheet.IsProtected); + + // Save the unprotected workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved as: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/working-with-tables/update-the-existing-table-comment-to-include-version-information-and-author-initials-for-documentation-tracking.cs b/working-with-tables/update-the-existing-table-comment-to-include-version-information-and-author-initials-for-documentation-tracking.cs new file mode 100644 index 0000000000..f9c5a10a68 --- /dev/null +++ b/working-with-tables/update-the-existing-table-comment-to-include-version-information-and-author-initials-for-documentation-tracking.cs @@ -0,0 +1,72 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class UpdateTableCommentDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the table (A1:B3) + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue(100); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue(200); + + // Add a ListObject (table) covering the data range + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int listObjectIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject listObject = worksheet.ListObjects[listObjectIndex]; + + // Existing comment (if any) can be retrieved; we now append version info and author initials + string existingComment = listObject.Comment ?? string.Empty; + string versionInfo = "v1.2"; + string authorInitials = "AB"; + + // Build the new comment string + // Example format: "Original comment. Version: v1.2, Author: AB" + string newComment = string.IsNullOrWhiteSpace(existingComment) + ? $"Version: {versionInfo}, Author: {authorInitials}" + : $"{existingComment} Version: {versionInfo}, Author: {authorInitials}"; + + // Update the table comment + listObject.Comment = newComment; + + // Output the updated comment to console for verification + Console.WriteLine("Updated Table Comment: " + listObject.Comment); + + // Save the workbook + workbook.Save("UpdatedTableComment.xlsx", SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred while updating the table comment: " + ex.Message); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + try + { + UpdateTableCommentDemo.Run(); + } + catch (Exception ex) + { + Console.WriteLine("Unhandled exception: " + ex.Message); + } + } + } +} \ No newline at end of file diff --git a/working-with-tables/update-the-named-range-that-references-a-table-after-expanding-the-table-to-include-new-rows.cs b/working-with-tables/update-the-named-range-that-references-a-table-after-expanding-the-table-to-include-new-rows.cs new file mode 100644 index 0000000000..7a226fe3b8 --- /dev/null +++ b/working-with-tables/update-the-named-range-that-references-a-table-after-expanding-the-table-to-include-new-rows.cs @@ -0,0 +1,58 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class UpdateNamedRangeAfterTableResize +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Name = "Data"; + + // Populate initial data for the table (2 columns, 5 rows) + for (int i = 0; i < 5; i++) + { + sheet.Cells[i, 0].PutValue($"Item {i + 1}"); + sheet.Cells[i, 1].PutValue((i + 1) * 10); + } + + // Create a table (ListObject) covering the initial data range A1:B5 + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 1, true); + ListObject table = sheet.ListObjects[tableIndex]; + table.DisplayName = "SalesTable"; + + // Create a named range that refers to the table's data range + int nameIndex = workbook.Worksheets.Names.Add("SalesData"); + Name namedRange = workbook.Worksheets.Names[nameIndex]; + // Set RefersTo without the leading '=' + namedRange.RefersTo = $"{sheet.Name}!{table.DataRange.RefersTo}"; + + // Expand the table by adding 3 more rows of data + for (int i = 5; i < 8; i++) + { + sheet.Cells[i, 0].PutValue($"Item {i + 1}"); + sheet.Cells[i, 1].PutValue((i + 1) * 10); + } + + // Resize the table to include the new rows (endRow = 7) + table.Resize(0, 0, 7, 1, true); + + // Update the named range to reference the new table range + // DataRange.RefersTo returns something like "$A$1:$B$8" + string newRefersTo = $"{table.DataRange.RefersTo}"; + // SetRefersTo expects the formula without leading '=', specify A1 style and global scope + namedRange.SetRefersTo($"{sheet.Name}!{newRefersTo}", false, false); + + // Save the workbook + workbook.Save("UpdatedNamedRange.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-listobjectputcellvalue-to-add-a-boolean-value-at-a-specific-row-and-column-offset-within-the-table.cs b/working-with-tables/use-listobjectputcellvalue-to-add-a-boolean-value-at-a-specific-row-and-column-offset-within-the-table.cs new file mode 100644 index 0000000000..80ffcc819d --- /dev/null +++ b/working-with-tables/use-listobjectputcellvalue-to-add-a-boolean-value-at-a-specific-row-and-column-offset-within-the-table.cs @@ -0,0 +1,42 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsListObjectBooleanDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Add header row for the table + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["C1"].PutValue("IsActive"); // Boolean column + + // Add some sample data rows + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["C2"].PutValue(false); // initial value + + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + worksheet.Cells["C3"].PutValue(false); // initial value + + // Create a ListObject (table) that includes the data range A1:C3 + int tableIndex = worksheet.ListObjects.Add("A1", "C3", true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Update the boolean value in the second data row (row offset 2, column offset 2) + // Row offset is zero‑based relative to the first data row (excluding header) + // Column offset is zero‑based relative to the first column of the table + table.PutCellValue(rowOffset: 2, columnOffset: 2, value: true); + + // Save the workbook to a file + workbook.Save("ListObjectBooleanDemo.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-listobjectputcellvalue-to-add-a-date-value-at-row-offset-two-and-column-offset-three.cs b/working-with-tables/use-listobjectputcellvalue-to-add-a-date-value-at-row-offset-two-and-column-offset-three.cs new file mode 100644 index 0000000000..dc7cb6fb35 --- /dev/null +++ b/working-with-tables/use-listobjectputcellvalue-to-add-a-date-value-at-row-offset-two-and-column-offset-three.cs @@ -0,0 +1,71 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsDemo +{ + public class ListObjectPutDateExample + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data that will become the table (including headers) + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["C1"].PutValue("Amount"); + worksheet.Cells["D1"].PutValue("Date"); // This column will receive the date via PutCellValue + + // Sample data rows + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["C2"].PutValue(100); + + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + worksheet.Cells["C3"].PutValue(200); + + // Add a ListObject (table) covering the range A1:D3, with headers + int startRow = 0; // Row index for "A1" + int startColumn = 0; // Column index for "A1" + int endRow = 2; // Row index for "D3" + int endColumn = 3; // Column index for "D3" + int tableIndex = worksheet.ListObjects.Add(startRow, startColumn, endRow, endColumn, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Insert a date value at row offset 2 (third data row) and column offset 3 (fourth column) + // The table will automatically expand by one row + DateTime dateToInsert = new DateTime(2023, 12, 31); + table.PutCellValue(2, 3, dateToInsert); + + // Format the newly added date cell + Style dateStyle = workbook.CreateStyle(); + dateStyle.Number = 14; // Built‑in date format + int newRowIndex = startRow + 1 + 2; // header row + offset + worksheet.Cells[newRowIndex, 3].SetStyle(dateStyle); + + // Save the workbook + workbook.Save("ListObjectPutDateDemo.xlsx", SaveFormat.Xlsx); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + ListObjectPutDateExample.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-listobjectputcellvalue-to-insert-a-hyperlink-string-into-a-specific-cell-of-the-table.cs b/working-with-tables/use-listobjectputcellvalue-to-insert-a-hyperlink-string-into-a-specific-cell-of-the-table.cs new file mode 100644 index 0000000000..87bf0055ae --- /dev/null +++ b/working-with-tables/use-listobjectputcellvalue-to-insert-a-hyperlink-string-into-a-specific-cell-of-the-table.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsHyperlinkInTable +{ + 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 sample data for the table (including header) + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B2"].PutValue("Alice"); + worksheet.Cells["A3"].PutValue(2); + worksheet.Cells["B3"].PutValue("Bob"); + + // Create a ListObject (table) that covers the data range A1:B3 + // Parameters: first row, first column, total rows, total columns, show header + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Define the row and column offset inside the table where the hyperlink will be placed + // For example, put hyperlink in the second data row (row offset 2) and second column (column offset 1) + int rowOffset = 2; // 0‑based offset from the start of the table (including header) + int columnOffset = 1; // second column (Name) + + // Insert the display text for the hyperlink using PutCellValue + table.PutCellValue(rowOffset, columnOffset, "Visit Aspose"); + + // Determine the absolute cell address (e.g., "B3") where the value was placed + int absoluteRow = table.StartRow + rowOffset; + int absoluteColumn = table.StartColumn + columnOffset; + string cellName = worksheet.Cells[absoluteRow, absoluteColumn].Name; // e.g., "B3" + + // Add a hyperlink to the same cell + // Parameters: cell name, total rows, total columns, hyperlink address + worksheet.Hyperlinks.Add(cellName, 1, 1, "https://www.aspose.com"); + + // Optionally, customize the displayed text (already set by PutCellValue) + // worksheet.Hyperlinks[worksheet.Hyperlinks.Count - 1].TextToDisplay = "Visit Aspose"; + + // Save the workbook + workbook.Save("TableWithHyperlink.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-listobjectputcellvalue-to-insert-a-string-value-into-a-table-cell-using-specific-row-and-column-offsets.cs b/working-with-tables/use-listobjectputcellvalue-to-insert-a-string-value-into-a-table-cell-using-specific-row-and-column-offsets.cs new file mode 100644 index 0000000000..fe78dcf4fb --- /dev/null +++ b/working-with-tables/use-listobjectputcellvalue-to-insert-a-string-value-into-a-table-cell-using-specific-row-and-column-offsets.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsListObjectPutCellValueDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate header row for the table + cells["A1"].PutValue("ID"); + cells["B1"].PutValue("Name"); + cells["C1"].PutValue("Description"); + + // Add a few data rows + cells["A2"].PutValue(1); + cells["B2"].PutValue("Alice"); + cells["C2"].PutValue("Initial description"); + + cells["A3"].PutValue(2); + cells["B3"].PutValue("Bob"); + cells["C3"].PutValue("Initial description"); + + // Create a ListObject (table) that covers the data range including the header + // Parameters: firstRow, firstColumn, totalRows, totalColumns, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 2, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Use PutCellValue to insert a string into a specific cell of the table + // rowOffset = 1 (second data row, because 0 is the header row) + // columnOffset = 2 (third column, "Description") + // value = new string to set + table.PutCellValue(rowOffset: 1, columnOffset: 2, value: "Updated description for Bob"); + + // Save the workbook to a file + workbook.Save("ListObjectPutCellValueDemo.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-listobjectputcellvalue-with-row-and-column-offsets-to-populate-a-header-cell-in-the-table.cs b/working-with-tables/use-listobjectputcellvalue-with-row-and-column-offsets-to-populate-a-header-cell-in-the-table.cs new file mode 100644 index 0000000000..7497250f9b --- /dev/null +++ b/working-with-tables/use-listobjectputcellvalue-with-row-and-column-offsets-to-populate-a-header-cell-in-the-table.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsListObjectHeaderDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate some sample data including initial header values + cells["A1"].PutValue("OldHeader1"); + cells["B1"].PutValue("OldHeader2"); + cells["A2"].PutValue(10); + cells["B2"].PutValue(20); + cells["A3"].PutValue(30); + cells["B3"].PutValue(40); + + // Add a ListObject (table) that includes the header row + // Parameters: startRow, startColumn, endRow, endColumn, hasHeaders + int tableIndex = worksheet.ListObjects.Add(0, 0, 2, 1, true); + ListObject table = worksheet.ListObjects[tableIndex]; + + // Use PutCellValue with row and column offsets to change a header cell. + // Row offset 0 = header row, column offset 0 = first column. + table.PutCellValue(0, 0, "NewHeader1"); + table.PutCellValue(0, 1, "NewHeader2"); + + // Save the workbook to a file + workbook.Save("ListObjectHeaderUpdated.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/working-with-tables/use-tabletorangeoptions-to-preserve-formatting-for-the-header-row-only-before-converting-the-table.cs b/working-with-tables/use-tabletorangeoptions-to-preserve-formatting-for-the-header-row-only-before-converting-the-table.cs new file mode 100644 index 0000000000..bad8074d0f --- /dev/null +++ b/working-with-tables/use-tabletorangeoptions-to-preserve-formatting-for-the-header-row-only-before-converting-the-table.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using System.Drawing; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsExamples +{ + public class PreserveHeaderFormattingDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate header row (row 0) and some data rows + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["C1"].PutValue("Score"); + + for (int i = 2; i <= 5; i++) + { + sheet.Cells[i - 1, 0].PutValue(i - 1); // ID + sheet.Cells[i - 1, 1].PutValue($"Person {i - 1}"); // Name + sheet.Cells[i - 1, 2].PutValue((i - 1) * 10); // Score + } + + // Create a table that includes the header and data rows + int tableIndex = sheet.ListObjects.Add(0, 0, 4, 2, true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Apply a distinct style to the header row to demonstrate preservation + Style headerStyle = workbook.CreateStyle(); + headerStyle.Font.IsBold = true; + headerStyle.ForegroundColor = Color.LightGray; + headerStyle.Pattern = BackgroundType.Solid; + for (int col = 0; col <= 2; col++) + { + Cell headerCell = sheet.Cells[0, col]; + headerCell.SetStyle(headerStyle); + } + + // Convert the table to a normal range. + // TableToRangeOptions does not expose PreserveFormatting in older versions, + // so we rely on the default behavior which keeps formatting. + TableToRangeOptions options = new TableToRangeOptions + { + // Limit conversion to the first row (header) only + LastRow = 0 + }; + table.ConvertToRange(options); + + // Define output file path + string outputPath = "PreserveHeaderFormatting.xlsx"; + + // Ensure the directory exists (handle possible null directory) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)) ?? string.Empty; + 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}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + PreserveHeaderFormattingDemo.Run(); + } + } +} \ No newline at end of file diff --git a/working-with-tables/validate-that-a-table-contains-no-duplicate-rows-based-on-a-combination-of-key-columns.cs b/working-with-tables/validate-that-a-table-contains-no-duplicate-rows-based-on-a-combination-of-key-columns.cs new file mode 100644 index 0000000000..5e7a1bea7e --- /dev/null +++ b/working-with-tables/validate-that-a-table-contains-no-duplicate-rows-based-on-a-combination-of-key-columns.cs @@ -0,0 +1,53 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsDuplicateValidation +{ + class Program + { + static void Main(string[] args) + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Determine the used range of the worksheet + int startRow = 0; // Assuming the first row contains headers + int startColumn = 0; + int endRow = cells.MaxDataRow; // Last row with data + int endColumn = cells.MaxDataColumn; // Last column with data + + // Record the original number of data rows (including header) + int originalRowCount = endRow - startRow + 1; + + // Define which columns constitute the key for duplicate detection. + // Example: first two columns (A and B) are the key columns. + int[] keyColumnOffsets = new int[] { 0, 1 }; + + // Perform duplicate removal on a copy of the range to test for duplicates. + // The method returns void, so we compare row counts before and after. + // hasHeaders = true because the first row is a header row. + cells.RemoveDuplicates(startRow + 1, startColumn, endRow, endColumn, true, keyColumnOffsets); + + // After removal, recalculate the last data row. + int newEndRow = cells.MaxDataRow; + int newRowCount = newEndRow - startRow + 1; + + // Validate: if row counts are equal, no duplicates existed; otherwise duplicates were present. + if (newRowCount == originalRowCount) + { + Console.WriteLine("Validation passed: No duplicate rows based on the key columns."); + } + else + { + Console.WriteLine($"Validation failed: {originalRowCount - newRowCount} duplicate row(s) were found and removed."); + } + + // Save the workbook (optional – the file now contains the deduplicated data) + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/working-with-tables/validate-that-a-tables-column-data-types-match-expected-net-types-before-importing-into-a-database.cs b/working-with-tables/validate-that-a-tables-column-data-types-match-expected-net-types-before-importing-into-a-database.cs new file mode 100644 index 0000000000..379844b3c6 --- /dev/null +++ b/working-with-tables/validate-that-a-tables-column-data-types-match-expected-net-types-before-importing-into-a-database.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Data; +using Aspose.Cells; + +namespace AsposeCellsColumnTypeValidation +{ + class Program + { + static void Main() + { + // Load the workbook that contains the source table + // (Replace \"input.xlsx\" with the actual path to your Excel file) + Workbook workbook = new Workbook("input.xlsx"); + Worksheet sheet = workbook.Worksheets[0]; + + // Define the expected .NET types for each column (by column header name) + // Example: "ID" should be Int32, "Name" should be String, "BirthDate" should be DateTime + var expectedColumnTypes = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "ID", typeof(int) }, + { "Name", typeof(string) }, + { "BirthDate", typeof(DateTime) }, + { "Salary", typeof(decimal) } + }; + + // Export the worksheet data to a DataTable. + // CheckMixedValueType = true forces Aspose.Cells to examine all rows + // and set the DataColumn type accordingly (or string if mixed). + ExportTableOptions exportOptions = new ExportTableOptions + { + ExportColumnName = true, // First row contains column names + CheckMixedValueType = true // Examine all rows for type detection + }; + + // Export the data range (adjust row/column count as needed) + DataTable dataTable = sheet.Cells.ExportDataTable(0, 0, sheet.Cells.MaxDataRow + 1, + sheet.Cells.MaxDataColumn + 1, exportOptions); + + // Validate each column's detected type against the expected type + foreach (DataColumn column in dataTable.Columns) + { + // Skip columns that are not part of the validation dictionary + if (!expectedColumnTypes.TryGetValue(column.ColumnName, out Type expectedType)) + { + Console.WriteLine($"Column \"{column.ColumnName}\" is not defined in expected types – skipping."); + continue; + } + + // Compare the detected DataColumn.DataType with the expected .NET type + if (column.DataType != expectedType) + { + Console.WriteLine($"Type mismatch in column \"{column.ColumnName}\": " + + $"expected {expectedType.Name}, detected {column.DataType.Name}."); + // Here you could decide to abort, convert, or handle the mismatch as needed. + // For demonstration we abort the import process. + Console.WriteLine("Aborting import due to type mismatch."); + return; + } + else + { + Console.WriteLine($"Column \"{column.ColumnName}\" type validated as {column.DataType.Name}."); + } + } + + // All columns validated – proceed with importing the data into the database. + // Example: using ImportData to write the DataTable back to another worksheet + // (replace with actual DB import logic as required). + Worksheet targetSheet = workbook.Worksheets.Add("ValidatedData"); + ImportTableOptions importOptions = new ImportTableOptions + { + IsFieldNameShown = true, + InsertRows = true, + ConvertNumericData = true + }; + targetSheet.Cells.ImportData(dataTable, 0, 0, importOptions); + + // Save the workbook with the validated data (optional) + workbook.Save("validated_output.xlsx"); + Console.WriteLine("Data validated and exported successfully."); + } + } +} \ No newline at end of file diff --git a/working-with-tables/validate-that-after-conversion-the-workbook-no-longer-contains-any-listobject-objects.cs b/working-with-tables/validate-that-after-conversion-the-workbook-no-longer-contains-any-listobject-objects.cs new file mode 100644 index 0000000000..1ebea2d0e7 --- /dev/null +++ b/working-with-tables/validate-that-after-conversion-the-workbook-no-longer-contains-any-listobject-objects.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data that will become a table + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + + // Add a ListObject (table) to the worksheet + int tableIndex = sheet.ListObjects.Add("A1", "B3", true); + ListObject table = sheet.ListObjects[tableIndex]; + + // Convert the ListObject to a normal range + table.ConvertToRange(); + + // Validate that the worksheet no longer contains any ListObject objects + if (sheet.ListObjects.Count == 0) + { + Console.WriteLine("Validation passed: No ListObject objects remain after conversion."); + } + else + { + Console.WriteLine($"Validation failed: {sheet.ListObjects.Count} ListObject(s) still present."); + } + + // Save the workbook (optional, demonstrates lifecycle usage) + workbook.Save("ValidatedWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/working-with-tables/verify-that-after-conversion-the-table-no-longer-supports-sorting-by-checking-listobjectistable-property.cs b/working-with-tables/verify-that-after-conversion-the-table-no-longer-supports-sorting-by-checking-listobjectistable-property.cs new file mode 100644 index 0000000000..3594e09757 --- /dev/null +++ b/working-with-tables/verify-that-after-conversion-the-table-no-longer-supports-sorting-by-checking-listobjectistable-property.cs @@ -0,0 +1,42 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; // Required for ListObject + +class VerifyTableConversion +{ + 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 the table + sheet.Cells["A1"].PutValue("ID"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("John"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Mary"); + + // Add a ListObject (table) covering the data range + int tableIndex = sheet.ListObjects.Add("A1", "B3", true); + ListObject listObject = sheet.ListObjects[tableIndex]; + + // Verify that the ListObject exists (it is a table at this point) + Console.WriteLine("Before conversion - ListObject count: " + sheet.ListObjects.Count); + + // Convert the table back to a normal range + listObject.ConvertToRange(); + + // After conversion the ListObject collection should be empty + bool tableStillExists = sheet.ListObjects.Count > 0; + Console.WriteLine("After conversion - ListObject exists in collection: " + tableStillExists); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/working-with-tables/write-a-datatable-object-into-a-new-worksheet-table-mapping-column-names-to-table-headers-automatically.cs b/working-with-tables/write-a-datatable-object-into-a-new-worksheet-table-mapping-column-names-to-table-headers-automatically.cs new file mode 100644 index 0000000000..202b71e1bf --- /dev/null +++ b/working-with-tables/write-a-datatable-object-into-a-new-worksheet-table-mapping-column-names-to-table-headers-automatically.cs @@ -0,0 +1,42 @@ +using System; +using System.Data; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a sample DataTable with column names and data + DataTable dt = new DataTable("Sample"); + dt.Columns.Add("Product", typeof(string)); + dt.Columns.Add("Quantity", typeof(int)); + dt.Columns.Add("Price", typeof(double)); + + dt.Rows.Add("Apple", 10, 0.5); + dt.Rows.Add("Banana", 20, 0.3); + dt.Rows.Add("Cherry", 15, 1.2); + + // Create a new workbook and get the first worksheet + Workbook wb = new Workbook(); + Worksheet ws = wb.Worksheets[0]; + + // Import the DataTable into the worksheet starting at cell A1. + // Set IsFieldNameShown = true so column names become table headers. + ImportTableOptions importOptions = new ImportTableOptions + { + IsFieldNameShown = true + }; + ws.Cells.ImportData(dt, 0, 0, importOptions); + + // Calculate the range that contains the imported data (including header row) + int totalRows = dt.Rows.Count + 1; // +1 for the header row + int totalCols = dt.Columns.Count; + + // Add an Excel table (ListObject) over the imported range. + // The last argument indicates that the first row is a header. + ws.ListObjects.Add(0, 0, totalRows, totalCols, true); + + // Save the workbook to a file. + wb.Save("DataTableToTable.xlsx"); + } +} \ No newline at end of file