diff --git a/index.json b/index.json index e6b002cd9b..083d28424f 100644 --- a/index.json +++ b/index.json @@ -5764,6 +5764,191 @@ "file": "load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs", "title": "Load a workbook that contains numerous unused styles and invoke RemoveUnusedStyles to clean it." }, + { + "category": "manage-workbook", + "file": "add-a-chart-to-a-worksheet-based-on-a-data-range-and-customize-its-legend-position.cs", + "title": "Add a chart to a worksheet based on a data range and customize its legend position." + }, + { + "category": "manage-workbook", + "file": "add-a-comment-to-a-cell-with-author-information-and-display-it-when-the-cell-is-selected.cs", + "title": "Add a comment to a cell with author information and display it when the cell is selected." + }, + { + "category": "manage-workbook", + "file": "add-a-custom-document-property-named-projectversion-and-assign-it-a-semantic-version-string.cs", + "title": "Add a custom document property named ProjectVersion and assign it a semantic version string." + }, + { + "category": "manage-workbook", + "file": "add-a-custom-xml-part-containing-metadata-and-retrieve-it-later-using-its-unique-identifier.cs", + "title": "Add a custom XML part containing metadata and retrieve it later using its unique identifier." + }, + { + "category": "manage-workbook", + "file": "add-a-new-contenttypeproperty-named-projectid-with-a-string-value-to-the-workbook.cs", + "title": "Add a new ContentTypeProperty named ProjectId with a string value to the workbook." + }, + { + "category": "manage-workbook", + "file": "add-multiple-custom-xml-parts-representing-different-data-sections-then-verify-each-appears-in-the-customxml-folder.cs", + "title": "Add multiple custom XML parts representing different data sections, then verify each appears in the customXml folder." + }, + { + "category": "manage-workbook", + "file": "after-adding-custom-properties-verify-that-the-workbooks-core-properties-remain-unchanged.cs", + "title": "After adding custom properties, verify that the workbook's core properties remain unchanged." + }, + { + "category": "manage-workbook", + "file": "after-processing-call-workbookdispose-explicitly-for-each-workbook-to-release-file-handles-and-memory.cs", + "title": "After processing, call Workbook.Dispose explicitly for each workbook to release file handles and memory." + }, + { + "category": "manage-workbook", + "file": "apply-a-filter-to-process-only-workbooks-that-already-contain-a-specific-custom-xml-part-before-modification.cs", + "title": "Apply a filter to process only workbooks that already contain a specific custom XML part before modification." + }, + { + "category": "manage-workbook", + "file": "apply-conditional-formatting-to-highlight-cells-containing-values-greater-than-a-specified-threshold.cs", + "title": "Apply conditional formatting to highlight cells containing values greater than a specified threshold." + }, + { + "category": "manage-workbook", + "file": "apply-data-validation-to-restrict-input-to-a-list-of-predefined-values-in-a-column.cs", + "title": "Apply data validation to restrict input to a list of predefined values in a column." + }, + { + "category": "manage-workbook", + "file": "benchmark-the-time-required-to-remove-unused-styles-from-workbooks-of-varying-size-to-determine-scaling-behavior.cs", + "title": "Benchmark the time required to remove unused styles from workbooks of varying size to determine scaling behavior." + }, + { + "category": "manage-workbook", + "file": "combine-adding-custom-xml-parts-with-style-cleanup-in-a-single-processing-pipeline-for-efficiency.cs", + "title": "Combine adding custom XML parts with style cleanup in a single processing pipeline for efficiency." + }, + { + "category": "manage-workbook", + "file": "compare-two-workbooks-one-with-unused-styles-removed-and-one-without-to-evaluate-visual-consistency.cs", + "title": "Compare two workbooks, one with unused styles removed and one without, to evaluate visual consistency." + }, + { + "category": "manage-workbook", + "file": "configure-the-workbook-to-use-a-specific-culture-when-formatting-optional-property-values-during-export.cs", + "title": "Configure the workbook to use a specific culture when formatting optional property values during export." + }, + { + "category": "manage-workbook", + "file": "configure-workbooksettings-to-disable-automatic-style-creation-before-removing-unused-styles-for-faster-cleanup.cs", + "title": "Configure WorkbookSettings to disable automatic style creation before removing unused styles for faster cleanup." + }, + { + "category": "manage-workbook", + "file": "copy-a-worksheet-from-the-source-workbook-to-a-destination-workbook-while-preserving-cell-styles.cs", + "title": "Copy a worksheet from the source workbook to a destination workbook while preserving cell styles." + }, + { + "category": "manage-workbook", + "file": "create-a-batch-job-that-processes-100-workbooks-adding-optional-metadata-and-removing-unused-styles.cs", + "title": "Create a batch job that processes 100 workbooks, adding optional metadata and removing unused styles." + }, + { + "category": "manage-workbook", + "file": "create-a-custom-xml-part-containing-a-book-catalog-schema-and-add-it-using-workbookcontenttypepropertiesadd.cs", + "title": "Create a custom XML part containing a book catalog schema and add it using Workbook.ContentTypeProperties.Add." + }, + { + "category": "manage-workbook", + "file": "create-a-named-range-that-spans-multiple-worksheets-and-use-it-in-a-summary-formula.cs", + "title": "Create a named range that spans multiple worksheets and use it in a summary formula." + }, + { + "category": "manage-workbook", + "file": "create-a-pivot-table-from-a-data-source-range-and-place-it-on-a-new-worksheet.cs", + "title": "Create a pivot table from a data source range and place it on a new worksheet." + }, + { + "category": "manage-workbook", + "file": "create-a-reusable-method-that-adds-a-contenttypeproperty-and-sets-isnillable-based-on-a-boolean-parameter.cs", + "title": "Create a reusable method that adds a ContentTypeProperty and sets IsNillable based on a boolean parameter." + }, + { + "category": "manage-workbook", + "file": "create-a-shared-workbook-instance-and-configure-it-for-concurrent-editing-by-multiple-users.cs", + "title": "Create a shared workbook instance and configure it for concurrent editing by multiple users." + }, + { + "category": "manage-workbook", + "file": "create-a-unit-test-that-asserts-the-isnillable-flag-is-true-for-a-given-contenttypeproperty-after-saving.cs", + "title": "Create a unit test that asserts the IsNillable flag is true for a given ContentTypeProperty after saving." + }, + { + "category": "manage-workbook", + "file": "enable-iterative-calculation-mode-and-set-maximum-iterations-to-improve-convergence-of-circular-formulas.cs", + "title": "Enable iterative calculation mode and set maximum iterations to improve convergence of circular formulas." + }, + { + "category": "manage-workbook", + "file": "export-a-list-of-all-contenttypeproperty-names-from-a-workbook-to-a-csv-file-for-reporting.cs", + "title": "Export a list of all ContentTypeProperty names from a workbook to a CSV file for reporting." + }, + { + "category": "manage-workbook", + "file": "export-a-specific-worksheet-to-an-image-file-with-300-dpi-resolution-and-transparent-background.cs", + "title": "Export a specific worksheet to an image file with 300 DPI resolution and transparent background." + }, + { + "category": "manage-workbook", + "file": "export-the-workbook-to-pdf-format-with-high-resolution-images-and-embedded-fonts.cs", + "title": "Export the workbook to PDF format with high resolution images and embedded fonts." + }, + { + "category": "manage-workbook", + "file": "generate-a-report-listing-workbooks-that-contain-optional-contenttypeproperties-lacking-the-isnillable-flag.cs", + "title": "Generate a report listing workbooks that contain optional ContentTypeProperties lacking the IsNillable flag." + }, + { + "category": "manage-workbook", + "file": "implement-a-commandline-tool-that-accepts-a-file-path-adds-an-optional-property-and-disposes-the-workbook.cs", + "title": "Implement a command\u2011line tool that accepts a file path, adds an optional property, and disposes the workbook." + }, + { + "category": "manage-workbook", + "file": "implement-error-handling-to-continue-batch-processing-when-a-workbook-fails-to-load-due-to-corruption.cs", + "title": "Implement error handling to continue batch processing when a workbook fails to load due to corruption." + }, + { + "category": "manage-workbook", + "file": "insert-a-hyperlink-into-a-cell-that-points-to-an-external-website-and-opens-in-a-new-tab.cs", + "title": "Insert a hyperlink into a cell that points to an external website and opens in a new tab." + }, + { + "category": "manage-workbook", + "file": "integrate-workbook-disposal-into-a-finally-block-to-guarantee-resource-release-even-when-exceptions-occur.cs", + "title": "Integrate workbook disposal into a finally block to guarantee resource release even when exceptions occur." + }, + { + "category": "manage-workbook", + "file": "iterate-through-multiple-workbooks-in-a-directory-adding-a-shared-contenttypeproperty-to-each-file.cs", + "title": "Iterate through multiple workbooks in a directory, adding a shared ContentTypeProperty to each file." + }, + { + "category": "manage-workbook", + "file": "load-a-csv-file-into-a-workbook-specify-the-delimiter-and-treat-the-first-row-as-headers.cs", + "title": "Load a CSV file into a workbook, specify the delimiter, and treat the first row as headers." + }, + { + "category": "manage-workbook", + "file": "load-a-workbook-from-a-memory-stream-modify-a-cell-value-and-write-back-to-the-stream.cs", + "title": "Load a workbook from a memory stream, modify a cell value, and write back to the stream." + }, + { + "category": "manage-workbook", + "file": "load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs", + "title": "Load a workbook that contains numerous unused styles and invoke RemoveUnusedStyles to clean it." + }, { "category": "manage-workbook", "file": "load-an-xlsx-workbook-from-a-file-stream-and-enable-automatic-formula-calculation.cs", diff --git a/manage-workbook/add-a-chart-to-a-worksheet-based-on-a-data-range-and-customize-its-legend-position.cs b/manage-workbook/add-a-chart-to-a-worksheet-based-on-a-data-range-and-customize-its-legend-position.cs new file mode 100644 index 0000000000..a3f1be5cc5 --- /dev/null +++ b/manage-workbook/add-a-chart-to-a-worksheet-based-on-a-data-range-and-customize-its-legend-position.cs @@ -0,0 +1,36 @@ +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]; + + // Add sample data for the chart + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Value"); + for (int i = 2; i <= 6; i++) + { + sheet.Cells[$"A{i}"].PutValue("Item " + (i - 1)); + sheet.Cells[$"B{i}"].PutValue((i - 1) * 10); + } + + // Add a column chart (rows 8‑20, columns 1‑8) + int chartIndex = sheet.Charts.Add(ChartType.Column, 7, 0, 19, 7); + Chart chart = sheet.Charts[chartIndex]; + + // Set the data range for the chart (A1:B6) and plot by column + chart.SetChartDataRange("A1:B6", true); + + // Customize the legend: place it at the bottom of the chart + chart.Legend.Position = LegendPositionType.Bottom; + chart.ShowLegend = true; // Ensure the legend is visible + + // Save the workbook with the chart + workbook.Save("ChartWithBottomLegend.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/manage-workbook/add-a-comment-to-a-cell-with-author-information-and-display-it-when-the-cell-is-selected.cs b/manage-workbook/add-a-comment-to-a-cell-with-author-information-and-display-it-when-the-cell-is-selected.cs new file mode 100644 index 0000000000..b27a2a2377 --- /dev/null +++ b/manage-workbook/add-a-comment-to-a-cell-with-author-information-and-display-it-when-the-cell-is-selected.cs @@ -0,0 +1,28 @@ +using Aspose.Cells; +using System; + +class AddCommentDemo +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Add a comment to cell A1 (creates the comment if it does not exist) + int commentIndex = worksheet.Comments.Add("A1"); + Comment comment = worksheet.Comments[commentIndex]; + + // Set the author and the comment text + comment.Author = "John Doe"; + comment.Note = "Reviewed by John Doe"; + + // Make the comment visible when the cell is selected + comment.IsVisible = true; + + // Save the workbook + workbook.Save("CommentWithAuthor.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/add-a-custom-document-property-named-projectversion-and-assign-it-a-semantic-version-string.cs b/manage-workbook/add-a-custom-document-property-named-projectversion-and-assign-it-a-semantic-version-string.cs new file mode 100644 index 0000000000..c298216403 --- /dev/null +++ b/manage-workbook/add-a-custom-document-property-named-projectversion-and-assign-it-a-semantic-version-string.cs @@ -0,0 +1,21 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +class AddCustomDocumentProperty +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add a custom document property named "ProjectVersion" with a semantic version string + workbook.CustomDocumentProperties.Add("ProjectVersion", "1.2.3"); + + // Display the added property value (optional) + Console.WriteLine("ProjectVersion: " + workbook.CustomDocumentProperties["ProjectVersion"].Value); + + // Save the workbook + workbook.Save("ProjectVersionDemo.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/manage-workbook/add-a-custom-xml-part-containing-metadata-and-retrieve-it-later-using-its-unique-identifier.cs b/manage-workbook/add-a-custom-xml-part-containing-metadata-and-retrieve-it-later-using-its-unique-identifier.cs new file mode 100644 index 0000000000..f6631efaa0 --- /dev/null +++ b/manage-workbook/add-a-custom-xml-part-containing-metadata-and-retrieve-it-later-using-its-unique-identifier.cs @@ -0,0 +1,50 @@ +using System; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +namespace AsposeCellsCustomXmlDemo +{ + class Program + { + static void Main() + { + // ---------- Create a new workbook ---------- + Workbook workbook = new Workbook(); + + // Sample XML data to store in the custom XML part + string xmlContent = "Sample Metadata"; + byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlContent); + + // Add the custom XML part (no schema data in this example) + int partIndex = workbook.CustomXmlParts.Add(xmlBytes, null); + + // Retrieve the added part and assign a unique identifier (GUID) + CustomXmlPart customPart = workbook.CustomXmlParts[partIndex]; + string uniqueId = Guid.NewGuid().ToString(); + customPart.ID = uniqueId; + + // Save the workbook containing the custom XML part + string filePath = "CustomXmlDemo.xlsx"; + workbook.Save(filePath); + + // ---------- Load the workbook and retrieve the custom XML part ---------- + Workbook loadedWorkbook = new Workbook(filePath); + + // Use the unique identifier to locate the custom XML part + CustomXmlPart retrievedPart = loadedWorkbook.CustomXmlParts.SelectByID(uniqueId); + + // Output verification information + if (retrievedPart != null) + { + Console.WriteLine("Retrieved Part ID: " + retrievedPart.ID); + string retrievedXml = Encoding.UTF8.GetString(retrievedPart.Data); + Console.WriteLine("Retrieved XML Content: " + retrievedXml); + } + else + { + Console.WriteLine("Custom XML part with ID not found."); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/add-a-new-contenttypeproperty-named-projectid-with-a-string-value-to-the-workbook.cs b/manage-workbook/add-a-new-contenttypeproperty-named-projectid-with-a-string-value-to-the-workbook.cs new file mode 100644 index 0000000000..1b0eb1d109 --- /dev/null +++ b/manage-workbook/add-a-new-contenttypeproperty-named-projectid-with-a-string-value-to-the-workbook.cs @@ -0,0 +1,19 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add a ContentTypeProperty named "ProjectId" with a string value + // The third parameter specifies the property type; using "string" here + workbook.ContentTypeProperties.Add("ProjectId", "MyProject123", "string"); + + // Save the workbook to a file + workbook.Save("ProjectWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/add-multiple-custom-xml-parts-representing-different-data-sections-then-verify-each-appears-in-the-customxml-folder.cs b/manage-workbook/add-multiple-custom-xml-parts-representing-different-data-sections-then-verify-each-appears-in-the-customxml-folder.cs new file mode 100644 index 0000000000..c2365f9e8f --- /dev/null +++ b/manage-workbook/add-multiple-custom-xml-parts-representing-different-data-sections-then-verify-each-appears-in-the-customxml-folder.cs @@ -0,0 +1,64 @@ +using System; +using System.Text; +using System.IO; +using System.IO.Compression; +using Aspose.Cells; +using Aspose.Cells.Markup; + +namespace AsposeCellsCustomXmlDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (creation rule) + Workbook workbook = new Workbook(); + + // Access the CustomXmlPartCollection + CustomXmlPartCollection customXmlParts = workbook.CustomXmlParts; + + // Define multiple XML data sections + string[] xmlDatas = new string[] + { + "Value1", + "Value2", + "Value3" + }; + + // Optional: define schemas (null in this example) + byte[] schemaBytes = null; + + // Add each XML part to the workbook + foreach (string xml in xmlDatas) + { + byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); + // Add method with byte[] data and optional schema (add rule) + customXmlParts.Add(xmlBytes, schemaBytes); + } + + // Save the workbook (save rule) + string outputPath = "MultipleCustomXmlParts.xlsx"; + workbook.Save(outputPath); + + // Verify the number of custom XML parts via the workbook API + Workbook reloadedWorkbook = new Workbook(outputPath); // load rule + Console.WriteLine("CustomXmlParts count (API): " + reloadedWorkbook.CustomXmlParts.Count); + + // Verify each part appears in the customXml folder inside the package + using (ZipArchive archive = ZipFile.OpenRead(outputPath)) + { + int customXmlEntryCount = 0; + Console.WriteLine("Entries in customXml folder:"); + foreach (ZipArchiveEntry entry in archive.Entries) + { + if (entry.FullName.StartsWith("customXml/", StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine("- " + entry.FullName); + customXmlEntryCount++; + } + } + Console.WriteLine("CustomXml folder entry count: " + customXmlEntryCount); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/after-adding-custom-properties-verify-that-the-workbooks-core-properties-remain-unchanged.cs b/manage-workbook/after-adding-custom-properties-verify-that-the-workbooks-core-properties-remain-unchanged.cs new file mode 100644 index 0000000000..3994455d9a --- /dev/null +++ b/manage-workbook/after-adding-custom-properties-verify-that-the-workbooks-core-properties-remain-unchanged.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +namespace AsposeCellsCustomPropertyVerification +{ + class Program + { + static void Main() + { + // Create a new workbook (uses the provided Workbook constructor rule) + Workbook workbook = new Workbook(); + + // Set some built‑in document properties that we will later verify remain unchanged + workbook.BuiltInDocumentProperties["Author"].Value = "Jane Doe"; + workbook.BuiltInDocumentProperties["Title"].Value = "Original Title"; + + // Capture the original built‑in property values + object originalAuthor = workbook.BuiltInDocumentProperties["Author"].Value; + object originalTitle = workbook.BuiltInDocumentProperties["Title"].Value; + + // Add custom document properties (uses the provided CustomDocumentProperties.Add rule) + workbook.CustomDocumentProperties.Add("Project", "AsposeDemo"); + workbook.CustomDocumentProperties.Add("Version", 1); + workbook.CustomDocumentProperties.Add("Reviewed", true); + workbook.CustomDocumentProperties.Add("GeneratedOn", DateTime.Now); + + // Verify that built‑in properties have not changed after adding custom properties + bool authorUnchanged = Equals(originalAuthor, workbook.BuiltInDocumentProperties["Author"].Value); + bool titleUnchanged = Equals(originalTitle, workbook.BuiltInDocumentProperties["Title"].Value); + + Console.WriteLine($"Author unchanged: {authorUnchanged}"); + Console.WriteLine($"Title unchanged: {titleUnchanged}"); + + // Save the workbook (uses the provided Save method rule) + workbook.Save("CustomPropertiesVerification.xlsx"); + + // Optional: Load the saved workbook to double‑check the properties + Workbook loaded = new Workbook("CustomPropertiesVerification.xlsx"); + Console.WriteLine($"Loaded Author: {loaded.BuiltInDocumentProperties["Author"].Value}"); + Console.WriteLine($"Loaded Title: {loaded.BuiltInDocumentProperties["Title"].Value}"); + Console.WriteLine($"Loaded Custom Property 'Project': {loaded.CustomDocumentProperties["Project"].Value}"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/after-processing-call-workbookdispose-explicitly-for-each-workbook-to-release-file-handles-and-memory.cs b/manage-workbook/after-processing-call-workbookdispose-explicitly-for-each-workbook-to-release-file-handles-and-memory.cs new file mode 100644 index 0000000000..f4b5f1fb00 --- /dev/null +++ b/manage-workbook/after-processing-call-workbookdispose-explicitly-for-each-workbook-to-release-file-handles-and-memory.cs @@ -0,0 +1,34 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Access the default worksheet and add some data + Worksheet ws = workbook.Worksheets[0]; + ws.Cells["A1"].PutValue("Hello Aspose.Cells!"); + + // Save the workbook to disk + workbook.Save("output.xlsx"); + + // Explicitly release unmanaged resources for this workbook + workbook.Dispose(); + + // Load the previously saved workbook + Workbook loadedWb = new Workbook("output.xlsx"); + + // Modify the loaded workbook + Worksheet loadedWs = loadedWb.Worksheets[0]; + loadedWs.Cells["B2"].PutValue("Modified"); + + // Save the modified workbook + loadedWb.Save("output_modified.xlsx"); + + // Explicitly release resources for the loaded workbook + loadedWb.Dispose(); + } +} \ No newline at end of file diff --git a/manage-workbook/agents.md b/manage-workbook/agents.md new file mode 100644 index 0000000000..1cf932da61 --- /dev/null +++ b/manage-workbook/agents.md @@ -0,0 +1,114 @@ +--- +category: manage-workbook +framework: .NET +parent: ../agents.md +version: v2 +--- + +# Persona + +You are a C# developer specializing in workbook management using Aspose.Cells for .NET. + +Generate simple, correct, production-quality examples that demonstrate ONE workbook-management 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; + +--- + +# Key APIs + +- Workbook +- WorkbookSettings +- WorksheetCollection +- Workbook.Worksheets +- SaveFormat + +--- + +# Common Pattern + +1. Create workbook +2. Configure workbook settings +3. Add or manage worksheets +4. Perform workbook operation +5. Save workbook +6. Print success message + +--- + +# Manage Workbook Rules + +- Use Workbook as the primary entry point +- Demonstrate one workbook-management feature per example +- Use programmatically generated workbook content +- Keep workbook operations focused and easy to understand + +--- + +# Input Strategy + +- Do NOT rely on external XLSX files +- Create workbook 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 workbook +- Configure workbook settings +- Add worksheets +- Remove worksheets +- Rename worksheets +- Manage workbook properties + +--- + +# Common Mistakes + +❌ var workbook = new Workbook(); +✅ Workbook workbook = new Workbook(); + +❌ Mix multiple workbook features in one example +✅ Demonstrate one workbook-management operation per example + +❌ Workbook workbook = new Workbook("input.xlsx"); +✅ Workbook workbook = new Workbook(); + +--- + +# Code Simplicity + +- Keep examples concise +- Avoid unnecessary abstractions + +--- + +# General Rules + +Refer to the root agents.md for: +- Boundaries +- Testing requirements +- Build and run instructions diff --git a/manage-workbook/apply-a-filter-to-process-only-workbooks-that-already-contain-a-specific-custom-xml-part-before-modification.cs b/manage-workbook/apply-a-filter-to-process-only-workbooks-that-already-contain-a-specific-custom-xml-part-before-modification.cs new file mode 100644 index 0000000000..9817da0ea8 --- /dev/null +++ b/manage-workbook/apply-a-filter-to-process-only-workbooks-that-already-contain-a-specific-custom-xml-part-before-modification.cs @@ -0,0 +1,47 @@ +using System; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +class ProcessWorkbookWithCustomXmlPart +{ + static void Main() + { + // Path to the source workbook + string inputPath = "input.xlsx"; + + // The ID of the custom XML part that must exist for processing + string requiredPartId = "2F087CB2-7CA8-43DA-B048-2E2F61F4936F"; + + // Load the workbook (using default LoadOptions) + LoadOptions loadOptions = new LoadOptions(); + Workbook workbook = new Workbook(inputPath, loadOptions); + + // Check if the workbook contains the required custom XML part + CustomXmlPart requiredPart = workbook.CustomXmlParts.SelectByID(requiredPartId); + + if (requiredPart != null) + { + // The required custom XML part exists – proceed with modifications + + // Example modification: add a new worksheet and write a message + int newSheetIndex = workbook.Worksheets.Add(); + Worksheet newSheet = workbook.Worksheets[newSheetIndex]; + newSheet.Name = "Processed"; + newSheet.Cells["A1"].PutValue("Workbook processed because required XML part was found."); + + // Save the modified workbook + string outputPath = "output.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook processed and saved to '{outputPath}'."); + } + else + { + // Required custom XML part not found – skip processing + Console.WriteLine("The workbook does not contain the required custom XML part. No changes were made."); + } + + // Clean up + workbook.Dispose(); + } +} \ No newline at end of file diff --git a/manage-workbook/apply-conditional-formatting-to-highlight-cells-containing-values-greater-than-a-specified-threshold.cs b/manage-workbook/apply-conditional-formatting-to-highlight-cells-containing-values-greater-than-a-specified-threshold.cs new file mode 100644 index 0000000000..d57c0474ed --- /dev/null +++ b/manage-workbook/apply-conditional-formatting-to-highlight-cells-containing-values-greater-than-a-specified-threshold.cs @@ -0,0 +1,54 @@ +using System; +using Aspose.Cells; +using System.Drawing; + +class ConditionalFormattingExample +{ + static void Main() + { + // Create a new workbook. + Workbook workbook = new Workbook(); + + // Get the first worksheet. + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample numeric data in column A (A1:A10). + for (int i = 0; i < 10; i++) + { + sheet.Cells[i, 0].PutValue(i * 10); // 0,10,20,...,90 + } + + // Define the cell area to which the conditional formatting will be applied. + CellArea range = new CellArea + { + StartRow = 0, + EndRow = 9, + StartColumn = 0, + EndColumn = 0 + }; + + // Add a new conditional formatting collection to the worksheet. + int cfIndex = sheet.ConditionalFormattings.Add(); + FormatConditionCollection fcc = sheet.ConditionalFormattings[cfIndex]; + + // Associate the defined range with the collection. + fcc.AddArea(range); + + // Specify the threshold value. + double threshold = 50; + + // Add a CellValue condition: highlight cells with values greater than the threshold. + int conditionIdx = fcc.AddCondition( + FormatConditionType.CellValue, + OperatorType.GreaterThan, + threshold.ToString(), + null); + FormatCondition condition = fcc[conditionIdx]; + + // Set the formatting style (e.g., light green background). + condition.Style.BackgroundColor = Color.LightGreen; + + // Save the workbook to a file. + workbook.Save("ConditionalFormattingGreaterThan.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/apply-data-validation-to-restrict-input-to-a-list-of-predefined-values-in-a-column.cs b/manage-workbook/apply-data-validation-to-restrict-input-to-a-list-of-predefined-values-in-a-column.cs new file mode 100644 index 0000000000..705e5b73dd --- /dev/null +++ b/manage-workbook/apply-data-validation-to-restrict-input-to-a-list-of-predefined-values-in-a-column.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Define the validation range: entire column B (rows 1‑100) + int startRow = 0; // Row 1 (zero‑based) + int endRow = 99; // Row 100 + int columnIndex = 1; // Column B (0 = A) + + CellArea area = CellArea.CreateCellArea(startRow, columnIndex, endRow, columnIndex); + + // Add a validation to the worksheet for the defined area + int validationIndex = sheet.Validations.Add(area); + Validation validation = sheet.Validations[validationIndex]; + + // Set validation as a list with predefined values + validation.Type = ValidationType.List; + validation.Formula1 = "Apple,Banana,Cherry"; + validation.InCellDropDown = true; // Show drop‑down list in cells + validation.ShowInput = true; // Show input message when cell is selected + validation.InputTitle = "Select Fruit"; + validation.InputMessage = "Choose a fruit from the list."; + validation.ShowError = true; // Show error dialog on invalid entry + validation.ErrorTitle = "Invalid Selection"; + validation.ErrorMessage = "Please select a value from the provided list."; + + // Save the workbook to a file + workbook.Save("ColumnListValidation.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/benchmark-the-time-required-to-remove-unused-styles-from-workbooks-of-varying-size-to-determine-scaling-behavior.cs b/manage-workbook/benchmark-the-time-required-to-remove-unused-styles-from-workbooks-of-varying-size-to-determine-scaling-behavior.cs new file mode 100644 index 0000000000..dd5566be07 --- /dev/null +++ b/manage-workbook/benchmark-the-time-required-to-remove-unused-styles-from-workbooks-of-varying-size-to-determine-scaling-behavior.cs @@ -0,0 +1,84 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using Aspose.Cells; + +class StyleRemovalBenchmark +{ + static void Main() + { + // Define different workbook sizes to test. + var testCases = new (int rows, int cols, int styleCount)[] + { + (100, 10, 100), // Small workbook + (500, 20, 500), // Medium workbook + (1000, 30, 1000) // Large workbook + }; + + foreach (var (rows, cols, styleCount) in testCases) + { + // Create a workbook populated with data and a pool of distinct styles. + Workbook wb = CreateWorkbook(rows, cols, styleCount); + + // Delete half of the rows to make some styles unused. + wb.Worksheets[0].Cells.DeleteRows(rows / 2, rows / 2); + + // Record the number of styles before removal. + int beforeCount = wb.CountOfStylesInPool; + Console.WriteLine($"Workbook {rows}x{cols}, styles before removal: {beforeCount}"); + + // Benchmark the RemoveUnusedStyles method. + Stopwatch sw = Stopwatch.StartNew(); + wb.RemoveUnusedStyles(); + sw.Stop(); + + // Record the number of styles after removal. + int afterCount = wb.CountOfStylesInPool; + Console.WriteLine($"After removal: {afterCount} styles, elapsed time: {sw.ElapsedMilliseconds} ms"); + + // Save the workbook to a memory stream (satisfies the save rule). + using (MemoryStream ms = new MemoryStream()) + { + wb.Save(ms, SaveFormat.Xlsx); + } + + Console.WriteLine(); + } + } + + // Creates a workbook with the specified number of rows, columns, and distinct styles. + static Workbook CreateWorkbook(int rows, int cols, int styleCount) + { + Workbook wb = new Workbook(); + Worksheet sheet = wb.Worksheets[0]; + Cells cells = sheet.Cells; + + // Prepare a pool of distinct styles. + Style[] stylePool = new Style[styleCount]; + Random rnd = new Random(0); + for (int i = 0; i < styleCount; i++) + { + Style style = wb.CreateStyle(); + style.Font.Name = "Arial"; + style.Font.Size = 10 + (i % 10); + style.Font.IsBold = (i % 2 == 0); + style.Font.Color = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)); + stylePool[i] = style; + } + + // Fill cells with data and assign a style from the pool. + for (int r = 0; r < rows; r++) + { + for (int c = 0; c < cols; c++) + { + Cell cell = cells[r, c]; + cell.PutValue($"R{r}C{c}"); + // Cycle through the style pool. + cell.SetStyle(stylePool[(r * cols + c) % styleCount]); + } + } + + return wb; + } +} \ No newline at end of file diff --git a/manage-workbook/combine-adding-custom-xml-parts-with-style-cleanup-in-a-single-processing-pipeline-for-efficiency.cs b/manage-workbook/combine-adding-custom-xml-parts-with-style-cleanup-in-a-single-processing-pipeline-for-efficiency.cs new file mode 100644 index 0000000000..03935b805b --- /dev/null +++ b/manage-workbook/combine-adding-custom-xml-parts-with-style-cleanup-in-a-single-processing-pipeline-for-efficiency.cs @@ -0,0 +1,57 @@ +using System; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +class Program +{ + static void Main() + { + // Create a new workbook (lifecycle create) + Workbook wb = new Workbook(); + + // Access the first worksheet + Worksheet sheet = wb.Worksheets[0]; + + // Populate cells with data and apply distinct styles + for (int i = 0; i < 10; i++) + { + Cell cell = sheet.Cells[i, 0]; + cell.PutValue($"Item {i + 1}"); + + // Create a style for each cell + Style style = wb.CreateStyle(); + style.Font.Name = "Arial"; + style.Font.Size = 10 + i; + style.Font.IsBold = (i % 2 == 0); + cell.SetStyle(style); + } + + // Delete rows to leave some styles unused (simulates real‑world cleanup) + sheet.Cells.DeleteRows(5, 5); + + // Prepare custom XML data and its schema + string xmlData = ""; + string xmlSchema = "" + + "" + + "" + + "" + + "" + + ""; + + byte[] dataBytes = Encoding.UTF8.GetBytes(xmlData); + byte[] schemaBytes = Encoding.UTF8.GetBytes(xmlSchema); + + // Add the custom XML part to the workbook (rule: CustomXmlPartCollection.Add) + int xmlPartIndex = wb.CustomXmlParts.Add(dataBytes, schemaBytes); + + // Optionally assign a unique ID to the added part + wb.CustomXmlParts[xmlPartIndex].ID = Guid.NewGuid().ToString(); + + // Remove all unused styles in one step (rule: Workbook.RemoveUnusedStyles) + wb.RemoveUnusedStyles(); + + // Save the workbook (lifecycle save) + wb.Save("CombinedOutput.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/compare-two-workbooks-one-with-unused-styles-removed-and-one-without-to-evaluate-visual-consistency.cs b/manage-workbook/compare-two-workbooks-one-with-unused-styles-removed-and-one-without-to-evaluate-visual-consistency.cs new file mode 100644 index 0000000000..0b13d137fc --- /dev/null +++ b/manage-workbook/compare-two-workbooks-one-with-unused-styles-removed-and-one-without-to-evaluate-visual-consistency.cs @@ -0,0 +1,70 @@ +using System; +using Aspose.Cells; +using System.Drawing; + +class CompareWorkbooks +{ + static void Main() + { + // Load the original workbook (contains all styles) + Workbook wbOriginal = new Workbook("Original.xlsx"); + + // Load a copy of the same workbook to remove unused styles + Workbook wbClean = new Workbook("Original.xlsx"); + + // Remove all unused styles from the copy + wbClean.RemoveUnusedStyles(); + + // Optional: save both workbooks for manual inspection + wbOriginal.Save("Original_Saved.xlsx"); + wbClean.Save("Clean_Saved.xlsx"); + + // Compare the number of styles in the style pool + int originalStyleCount = wbOriginal.CountOfStylesInPool; + int cleanStyleCount = wbClean.CountOfStylesInPool; + Console.WriteLine($"Original style count: {originalStyleCount}"); + Console.WriteLine($"Clean style count: {cleanStyleCount}"); + + // Get the first worksheets from both workbooks + Worksheet wsOriginal = wbOriginal.Worksheets[0]; + Worksheet wsClean = wbClean.Worksheets[0]; + + Cells cellsOriginal = wsOriginal.Cells; + Cells cellsClean = wsClean.Cells; + + // Determine the range to compare (max used rows/columns in either workbook) + int maxRow = Math.Max(cellsOriginal.MaxDataRow, cellsClean.MaxDataRow); + int maxCol = Math.Max(cellsOriginal.MaxDataColumn, cellsClean.MaxDataColumn); + + bool allStylesMatch = true; + + // Iterate through each cell in the determined range + for (int row = 0; row <= maxRow; row++) + { + for (int col = 0; col <= maxCol; col++) + { + Cell cellOrig = cellsOriginal[row, col]; + Cell cellClean = cellsClean[row, col]; + + // Retrieve the display style of each cell (including merged borders) + Style styleOrig = cellOrig.GetDisplayStyle(true); + Style styleClean = cellClean.GetDisplayStyle(true); + + // Compare the two styles using Style.Equals + if (!styleOrig.Equals(styleClean)) + { + allStylesMatch = false; + Console.WriteLine($"Style mismatch at cell {cellOrig.Name}:"); + Console.WriteLine($" Original Font: {styleOrig.Font.Name}, Size {styleOrig.Font.Size}, Color {styleOrig.Font.Color}"); + Console.WriteLine($" Clean Font: {styleClean.Font.Name}, Size {styleClean.Font.Size}, Color {styleClean.Font.Color}"); + } + } + } + + // Report the overall visual consistency result + if (allStylesMatch) + Console.WriteLine("All cell display styles are visually consistent after removing unused styles."); + else + Console.WriteLine("Some cell display styles differ after removing unused styles."); + } +} \ No newline at end of file diff --git a/manage-workbook/configure-the-workbook-to-use-a-specific-culture-when-formatting-optional-property-values-during-export.cs b/manage-workbook/configure-the-workbook-to-use-a-specific-culture-when-formatting-optional-property-values-during-export.cs new file mode 100644 index 0000000000..b5b2fcaabe --- /dev/null +++ b/manage-workbook/configure-the-workbook-to-use-a-specific-culture-when-formatting-optional-property-values-during-export.cs @@ -0,0 +1,32 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsCultureDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (creation rule) + Workbook workbook = new Workbook(); + + // Set the desired culture for formatting optional property values + // For example, French (France) uses space as group separator and comma as decimal separator + workbook.Settings.CultureInfo = new CultureInfo("fr-FR"); + + // Optional: demonstrate the effect by adding a number and applying a custom style + Worksheet sheet = workbook.Worksheets[0]; + Cell cell = sheet.Cells["A1"]; + cell.PutValue(1234567.89); // Value to be formatted + + // Create a style with a custom numeric format + Style style = workbook.CreateStyle(); + style.Custom = "#,##0.00"; // Uses the workbook's culture settings + cell.SetStyle(style); + + // Save the workbook (save rule) + workbook.Save("Workbook_With_FrenchCulture.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/configure-workbooksettings-to-disable-automatic-style-creation-before-removing-unused-styles-for-faster-cleanup.cs b/manage-workbook/configure-workbooksettings-to-disable-automatic-style-creation-before-removing-unused-styles-for-faster-cleanup.cs new file mode 100644 index 0000000000..2ae8d9abc7 --- /dev/null +++ b/manage-workbook/configure-workbooksettings-to-disable-automatic-style-creation-before-removing-unused-styles-for-faster-cleanup.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class DisableAutoStyleAndCleanup + { + public static void Run() + { + try + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Add sample data with different styles to generate a style pool + for (int i = 0; i < 10; i++) + { + Cell cell = sheet.Cells[i, 0]; + cell.PutValue($"Item {i + 1}"); + + // Create a distinct style for each cell + Style style = workbook.CreateStyle(); + style.Font.Name = "Arial"; + style.Font.Size = 10 + i; + style.Font.IsBold = i % 2 == 0; + cell.SetStyle(style); + } + + // Delete some rows to leave unused styles in the pool + sheet.Cells.DeleteRows(5, 5); + + // NOTE: In older Aspose.Cells versions the property + // WorkbookSettings.EnableAutomaticStyleCreation does not exist. + // The cleanup works without explicitly disabling it. + + // Remove all styles that are no longer referenced by any cell + workbook.RemoveUnusedStyles(); + + // Save the cleaned workbook + string outputPath = "CleanedWorkbook.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 to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Application entry point + public class Program + { + public static void Main(string[] args) + { + DisableAutoStyleAndCleanup.Run(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/copy-a-worksheet-from-the-source-workbook-to-a-destination-workbook-while-preserving-cell-styles.cs b/manage-workbook/copy-a-worksheet-from-the-source-workbook-to-a-destination-workbook-while-preserving-cell-styles.cs new file mode 100644 index 0000000000..f9e8a7db58 --- /dev/null +++ b/manage-workbook/copy-a-worksheet-from-the-source-workbook-to-a-destination-workbook-while-preserving-cell-styles.cs @@ -0,0 +1,27 @@ +using System; +using Aspose.Cells; + +class CopyWorksheetDemo +{ + static void Main() + { + // Load the source workbook from a file + Workbook sourceWorkbook = new Workbook("source.xlsx"); + + // Create a new (empty) destination workbook + Workbook destWorkbook = new Workbook(); + + // Get the source worksheet (e.g., the first sheet) + Worksheet sourceSheet = sourceWorkbook.Worksheets[0]; + + // Get the destination worksheet (the first sheet in the new workbook) + Worksheet destSheet = destWorkbook.Worksheets[0]; + + // Copy the source worksheet into the destination worksheet. + // This method copies both the cell values and their styles. + destSheet.Copy(sourceSheet); + + // Save the destination workbook to a file + destWorkbook.Save("destination.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-batch-job-that-processes-100-workbooks-adding-optional-metadata-and-removing-unused-styles.cs b/manage-workbook/create-a-batch-job-that-processes-100-workbooks-adding-optional-metadata-and-removing-unused-styles.cs new file mode 100644 index 0000000000..5790b5690e --- /dev/null +++ b/manage-workbook/create-a-batch-job-that-processes-100-workbooks-adding-optional-metadata-and-removing-unused-styles.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Metadata; + +namespace BatchWorkbookProcessor +{ + class Program + { + static void Main() + { + // Directory containing the source workbooks + string sourceDir = @"C:\Workbooks\Source"; + // Directory where processed workbooks will be saved + string outputDir = @"C:\Workbooks\Processed"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputDir); + + // Process 100 workbooks named Workbook1.xlsx ... Workbook100.xlsx + for (int i = 1; i <= 100; i++) + { + string inputPath = Path.Combine(sourceDir, $"Workbook{i}.xlsx"); + string outputPath = Path.Combine(outputDir, $"Workbook{i}_Processed.xlsx"); + string tempMetaPath = Path.Combine(outputDir, $"Workbook{i}_TempMeta.xlsx"); + + try + { + // Verify source file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Source file not found: {inputPath}"); + continue; + } + + // Load the workbook + using (Workbook wb = new Workbook(inputPath)) + { + // OPTIONAL: Add custom metadata using WorkbookMetadata + MetadataOptions metaOptions = new MetadataOptions(MetadataType.DocumentProperties); + WorkbookMetadata metadata = new WorkbookMetadata(inputPath, metaOptions); + + // Add custom document properties + metadata.CustomDocumentProperties.Add("ProcessedOn", DateTime.UtcNow.ToString("o")); + metadata.CustomDocumentProperties.Add("ProcessedBy", "BatchJob"); + + // Save metadata to a temporary file + metadata.Save(tempMetaPath); + + // Reload workbook with updated metadata + wb.Dispose(); // Dispose original workbook before reloading + using (Workbook wbMeta = new Workbook(tempMetaPath)) + { + // Remove all unused styles + wbMeta.RemoveUnusedStyles(); + + // Save the final processed workbook + wbMeta.Save(outputPath); + } + } + + // Clean up temporary file + if (File.Exists(tempMetaPath)) + { + File.Delete(tempMetaPath); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error processing Workbook{i}: {ex.Message}"); + } + } + + Console.WriteLine("Batch processing of 100 workbooks completed."); + } + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-custom-xml-part-containing-a-book-catalog-schema-and-add-it-using-workbookcontenttypepropertiesadd.cs b/manage-workbook/create-a-custom-xml-part-containing-a-book-catalog-schema-and-add-it-using-workbookcontenttypepropertiesadd.cs new file mode 100644 index 0000000000..83002aaec5 --- /dev/null +++ b/manage-workbook/create-a-custom-xml-part-containing-a-book-catalog-schema-and-add-it-using-workbookcontenttypepropertiesadd.cs @@ -0,0 +1,73 @@ +using System; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +namespace AsposeCellsCustomXmlDemo +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Sample XML data representing a simple book catalog + string xmlData = @" + + + Gambardella, Matthew + XML Developer's Guide + Computer + 44.95 + 2000-10-01 + An in-depth look at creating applications with XML. + +"; + + // Corresponding XML schema (XSD) for the catalog + string xmlSchema = @" + + + + + + + + + + + + + + + + + + + + + +"; + + // Convert XML and schema strings to UTF-8 byte arrays + byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlData); + byte[] schemaBytes = Encoding.UTF8.GetBytes(xmlSchema); + + // Add the custom XML part to the workbook using the provided API + int partIndex = workbook.CustomXmlParts.Add(xmlBytes, schemaBytes); + + // Optional: retrieve the part to verify its ID or content + CustomXmlPart addedPart = workbook.CustomXmlParts[partIndex]; + Console.WriteLine($"Custom XML part added at index {partIndex}, ID: {addedPart.ID}"); + + // Save the workbook to a file + string outputPath = "BookCatalogWorkbook.xlsx"; + workbook.Save(outputPath); + + // Load the workbook back to confirm the custom XML part persists + Workbook loadedWorkbook = new Workbook(outputPath); + Console.WriteLine($"Loaded workbook contains {loadedWorkbook.CustomXmlParts.Count} custom XML part(s)."); + } + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-named-range-that-spans-multiple-worksheets-and-use-it-in-a-summary-formula.cs b/manage-workbook/create-a-named-range-that-spans-multiple-worksheets-and-use-it-in-a-summary-formula.cs new file mode 100644 index 0000000000..dd341a799c --- /dev/null +++ b/manage-workbook/create-a-named-range-that-spans-multiple-worksheets-and-use-it-in-a-summary-formula.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsMultiSheetNamedRange +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add two worksheets (Sheet1 already exists) + Worksheet sheet1 = workbook.Worksheets[0]; + sheet1.Name = "Sheet1"; + Worksheet sheet2 = workbook.Worksheets.Add("Sheet2"); + + // Populate some sample data in both sheets + // Sheet1: A1:A3 = 10, 20, 30 + sheet1.Cells["A1"].PutValue(10); + sheet1.Cells["A2"].PutValue(20); + sheet1.Cells["A3"].PutValue(30); + + // Sheet2: A1:A3 = 5, 15, 25 + sheet2.Cells["A1"].PutValue(5); + sheet2.Cells["A2"].PutValue(15); + sheet2.Cells["A3"].PutValue(25); + + // Create a named range that spans both worksheets + // The RefersTo string uses a comma to separate the areas + int nameIndex = workbook.Worksheets.Names.Add("MultiRange"); + Name multiRange = workbook.Worksheets.Names[nameIndex]; + multiRange.RefersTo = "=Sheet1!$A$1:$A$3,Sheet2!$A$1:$A$3"; + + // Use the named range in a summary formula (sum of all cells in the range) + // Place the formula in Sheet1!B1 + sheet1.Cells["B1"].Formula = "=SUM(MultiRange)"; + + // Calculate formulas so that the result is available + workbook.CalculateFormula(); + + // Output the calculated result to console + Console.WriteLine("Sum of MultiRange (Sheet1!A1:A3 + Sheet2!A1:A3) = " + sheet1.Cells["B1"].Value); + + // Save the workbook + workbook.Save("MultiSheetNamedRangeDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-pivot-table-from-a-data-source-range-and-place-it-on-a-new-worksheet.cs b/manage-workbook/create-a-pivot-table-from-a-data-source-range-and-place-it-on-a-new-worksheet.cs new file mode 100644 index 0000000000..90f626e680 --- /dev/null +++ b/manage-workbook/create-a-pivot-table-from-a-data-source-range-and-place-it-on-a-new-worksheet.cs @@ -0,0 +1,83 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsPivotDemo +{ + public class CreatePivotTable + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet and add sample data + 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"); + + sourceSheet.Cells["A2"].PutValue("Fruit"); + sourceSheet.Cells["B2"].PutValue("Apple"); + sourceSheet.Cells["C2"].PutValue(1200); + + sourceSheet.Cells["A3"].PutValue("Fruit"); + sourceSheet.Cells["B3"].PutValue("Banana"); + sourceSheet.Cells["C3"].PutValue(850); + + sourceSheet.Cells["A4"].PutValue("Vegetable"); + sourceSheet.Cells["B4"].PutValue("Carrot"); + sourceSheet.Cells["C4"].PutValue(560); + + sourceSheet.Cells["A5"].PutValue("Vegetable"); + sourceSheet.Cells["B5"].PutValue("Broccoli"); + sourceSheet.Cells["C5"].PutValue(430); + + // Add a new worksheet that will host the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("PivotTable"); + + // Determine the source data range (including headers) + Aspose.Cells.Range sourceRange = sourceSheet.Cells.MaxDisplayRange; + string sourceData = $"=SourceData!{sourceRange.Address}"; + + // Add the pivot table to the new worksheet + PivotTableCollection pivotTables = pivotSheet.PivotTables; + int pivotIndex = pivotTables.Add(sourceData, "A1", "SalesPivot"); + + // Retrieve the created pivot table + PivotTable pivotTable = pivotTables[pivotIndex]; + + // Configure the pivot table fields + pivotTable.AddFieldToArea(PivotFieldType.Row, "Category"); + pivotTable.AddFieldToArea(PivotFieldType.Column, "Product"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Sales"); + + // Refresh the pivot table to calculate and display data + pivotSheet.RefreshPivotTables(); + + // Save the workbook + string outputPath = "PivotTableDemo.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) + { + CreatePivotTable.Run(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-reusable-method-that-adds-a-contenttypeproperty-and-sets-isnillable-based-on-a-boolean-parameter.cs b/manage-workbook/create-a-reusable-method-that-adds-a-contenttypeproperty-and-sets-isnillable-based-on-a-boolean-parameter.cs new file mode 100644 index 0000000000..4bbaa2f8c8 --- /dev/null +++ b/manage-workbook/create-a-reusable-method-that-adds-a-contenttypeproperty-and-sets-isnillable-based-on-a-boolean-parameter.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +public static class ContentTypeHelper +{ + // Adds a content type property to the workbook and sets its IsNillable flag. + public static void AddContentTypeProperty(Workbook workbook, string name, string value, string type, bool isNillable) + { + // Add the property; the overload with type returns the index of the new property. + int index = workbook.ContentTypeProperties.Add(name, value, type); + // Retrieve the property by index and set IsNillable. + workbook.ContentTypeProperties[index].IsNillable = isNillable; + } +} + +class Program +{ + static void Main() + { + // Create a new workbook. + Workbook wb = new Workbook(); + + // Add a property that can be empty. + ContentTypeHelper.AddContentTypeProperty(wb, "Admin", "Aspose", "text", true); + + // Add a property that cannot be empty. + ContentTypeHelper.AddContentTypeProperty(wb, "Version", "1.0", "number", false); + + // Save the workbook. + wb.Save("ContentTypePropertiesDemo.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-shared-workbook-instance-and-configure-it-for-concurrent-editing-by-multiple-users.cs b/manage-workbook/create-a-shared-workbook-instance-and-configure-it-for-concurrent-editing-by-multiple-users.cs new file mode 100644 index 0000000000..ab18d987fd --- /dev/null +++ b/manage-workbook/create-a-shared-workbook-instance-and-configure-it-for-concurrent-editing-by-multiple-users.cs @@ -0,0 +1,27 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Enable shared mode for concurrent editing by multiple users + workbook.Settings.Shared = true; + + // Optional: add some sample data + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Shared Workbook"); + sheet.Cells["A2"].PutValue(DateTime.Now); + + // Save the shared workbook + string filePath = "SharedWorkbook.xlsx"; + workbook.Save(filePath); + + // Load the workbook to verify that the Shared property is set + Workbook loadedWorkbook = new Workbook(filePath); + Console.WriteLine("Shared property value: " + loadedWorkbook.Settings.Shared); + } +} \ No newline at end of file diff --git a/manage-workbook/create-a-unit-test-that-asserts-the-isnillable-flag-is-true-for-a-given-contenttypeproperty-after-saving.cs b/manage-workbook/create-a-unit-test-that-asserts-the-isnillable-flag-is-true-for-a-given-contenttypeproperty-after-saving.cs new file mode 100644 index 0000000000..21f08f8442 --- /dev/null +++ b/manage-workbook/create-a-unit-test-that-asserts-the-isnillable-flag-is-true-for-a-given-contenttypeproperty-after-saving.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsTests +{ + class Program + { + private const string PropertyName = "Admin"; + private const string PropertyValue = "Aspose"; + private const string PropertyType = "text"; + + static void Main() + { + string tempFile = null; + + try + { + // Create a new workbook and add a content type property + var workbook = new Workbook(); + workbook.ContentTypeProperties.Add(PropertyName, PropertyValue, PropertyType); + + // Retrieve the added property and set IsNillable flag + var property = workbook.ContentTypeProperties[PropertyName]; + property.IsNillable = true; + + // Save the workbook to a temporary file + tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xlsx"); + workbook.Save(tempFile); + + // Ensure the file was created before attempting to load it + if (!File.Exists(tempFile)) + { + Console.WriteLine("Temporary file was not created."); + return; + } + + // Load the saved workbook + var loadedWorkbook = new Workbook(tempFile); + var loadedProperty = loadedWorkbook.ContentTypeProperties[PropertyName]; + + // Verify that IsNillable remains true after loading + if (loadedProperty.IsNillable) + { + Console.WriteLine("Test passed: IsNillable is true after saving and loading."); + } + else + { + Console.WriteLine("Test failed: IsNillable is false after saving and loading."); + } + } + catch (Exception ex) + { + // Runtime safety: capture any unexpected errors + Console.WriteLine($"Exception: {ex.Message}"); + } + finally + { + // Cleanup: delete the temporary file if it exists + if (!string.IsNullOrEmpty(tempFile) && File.Exists(tempFile)) + { + try + { + File.Delete(tempFile); + } + catch + { + // Suppress any cleanup errors + } + } + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/enable-iterative-calculation-mode-and-set-maximum-iterations-to-improve-convergence-of-circular-formulas.cs b/manage-workbook/enable-iterative-calculation-mode-and-set-maximum-iterations-to-improve-convergence-of-circular-formulas.cs new file mode 100644 index 0000000000..8ccab8f352 --- /dev/null +++ b/manage-workbook/enable-iterative-calculation-mode-and-set-maximum-iterations-to-improve-convergence-of-circular-formulas.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsIterativeDemo +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Enable iterative calculation to resolve circular references + workbook.Settings.FormulaSettings.EnableIterativeCalculation = true; + + // Set the maximum number of iterations for convergence + workbook.Settings.FormulaSettings.MaxIteration = 100; + + // (Optional) Define the maximum change threshold for convergence + workbook.Settings.FormulaSettings.MaxChange = 0.001; + + // Set up a simple circular reference scenario + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].Formula = "=A2+1"; + sheet.Cells["A2"].Formula = "=A1+1"; + + // Perform formula calculation using the configured settings + workbook.CalculateFormula(); + + // Display the calculated values + Console.WriteLine("A1 value: " + sheet.Cells["A1"].Value); + Console.WriteLine("A2 value: " + sheet.Cells["A2"].Value); + + // Save the workbook (optional) + workbook.Save("IterativeDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/export-a-list-of-all-contenttypeproperty-names-from-a-workbook-to-a-csv-file-for-reporting.cs b/manage-workbook/export-a-list-of-all-contenttypeproperty-names-from-a-workbook-to-a-csv-file-for-reporting.cs new file mode 100644 index 0000000000..69c7b7208f --- /dev/null +++ b/manage-workbook/export-a-list-of-all-contenttypeproperty-names-from-a-workbook-to-a-csv-file-for-reporting.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Properties; + +namespace AsposeCellsExamples +{ + public class ExportContentTypePropertyNamesToCsv + { + public static void Run(string workbookPath, string csvOutputPath) + { + try + { + // Verify input workbook exists + if (!File.Exists(workbookPath)) + { + Console.WriteLine($"Workbook file not found: {workbookPath}"); + return; + } + + // Load the existing workbook + Workbook workbook = new Workbook(workbookPath); + + // Ensure output directory exists + string outDir = Path.GetDirectoryName(csvOutputPath); + if (!string.IsNullOrEmpty(outDir) && !Directory.Exists(outDir)) + { + Directory.CreateDirectory(outDir); + } + + // Write each ContentTypeProperty name to the CSV file + using (StreamWriter writer = new StreamWriter(csvOutputPath)) + { + foreach (ContentTypeProperty property in workbook.ContentTypeProperties) + { + writer.WriteLine(property.Name); + } + } + + Console.WriteLine($"Content type property names exported to: {csvOutputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + // Expect two arguments: input workbook path and output CSV path + if (args.Length < 2) + { + Console.WriteLine("Usage: AsposeCellsRunner "); + return; + } + + string workbookPath = args[0]; + string csvOutputPath = args[1]; + + ExportContentTypePropertyNamesToCsv.Run(workbookPath, csvOutputPath); + } + } +} \ No newline at end of file diff --git a/manage-workbook/export-a-specific-worksheet-to-an-image-file-with-300-dpi-resolution-and-transparent-background.cs b/manage-workbook/export-a-specific-worksheet-to-an-image-file-with-300-dpi-resolution-and-transparent-background.cs new file mode 100644 index 0000000000..1caf263190 --- /dev/null +++ b/manage-workbook/export-a-specific-worksheet-to-an-image-file-with-300-dpi-resolution-and-transparent-background.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; +using Aspose.Cells.Drawing; + +class ExportWorksheetToImage +{ + static void Main() + { + // Load the workbook (replace with your actual file path) + string workbookPath = "input.xlsx"; + Workbook workbook = new Workbook(workbookPath); + + // Select the worksheet to export (by index or name) + int sheetIndex = 0; // first worksheet + Worksheet sheet = workbook.Worksheets[sheetIndex]; + + // Set up image rendering options + ImageOrPrintOptions options = new ImageOrPrintOptions(); + options.ImageType = ImageType.Png; // PNG supports transparency + options.HorizontalResolution = 300; // 300 DPI horizontal + options.VerticalResolution = 300; // 300 DPI vertical + options.Transparent = true; // make background transparent + options.OnePagePerSheet = true; // render the whole sheet on one page + + // Create a SheetRender instance for the selected worksheet + SheetRender renderer = new SheetRender(sheet, options); + + // Define the output image file path + string imagePath = "output_sheet.png"; + + // Render the first (and only) page of the worksheet to the image file + renderer.ToImage(0, imagePath); + + Console.WriteLine($"Worksheet exported successfully to: {imagePath}"); + } +} \ No newline at end of file diff --git a/manage-workbook/export-the-workbook-to-pdf-format-with-high-resolution-images-and-embedded-fonts.cs b/manage-workbook/export-the-workbook-to-pdf-format-with-high-resolution-images-and-embedded-fonts.cs new file mode 100644 index 0000000000..8d5bdea4ab --- /dev/null +++ b/manage-workbook/export-the-workbook-to-pdf-format-with-high-resolution-images-and-embedded-fonts.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; + +class ExportWorkbookToPdf +{ + 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 + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("Fruits"); + worksheet.Cells["A3"].PutValue("Vegetables"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(50); + worksheet.Cells["B3"].PutValue(30); + + // Add a column chart + int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart = worksheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B3", true); + chart.NSeries.CategoryData = "A2:A3"; + + // Configure PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + // Embed standard Windows fonts + EmbedStandardWindowsFonts = true, + // Fallback font for Unicode characters + DefaultFont = "Arial", + CheckWorkbookDefaultFont = true + // Note: ImageResolution and JpegQuality properties are not available in the current Aspose.Cells version + }; + + // Define output file path + string outputPath = "output_highres_embeddedfonts.pdf"; + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the workbook as PDF + workbook.Save(outputPath, pdfOptions); + Console.WriteLine($"PDF saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/generate-a-report-listing-workbooks-that-contain-optional-contenttypeproperties-lacking-the-isnillable-flag.cs b/manage-workbook/generate-a-report-listing-workbooks-that-contain-optional-contenttypeproperties-lacking-the-isnillable-flag.cs new file mode 100644 index 0000000000..164d1d707a --- /dev/null +++ b/manage-workbook/generate-a-report-listing-workbooks-that-contain-optional-contenttypeproperties-lacking-the-isnillable-flag.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Properties; + +class ContentTypePropertiesReport +{ + static void Main() + { + try + { + // Folder containing the workbooks to be inspected + string folderPath = @"C:\Workbooks"; + + // Output CSV file for the report + string reportPath = @"C:\Report\ContentTypePropertiesReport.csv"; + + // Prepare a list to hold report lines (CSV header + data) + List reportLines = new List + { + "Workbook,PropertyName,PropertyType,PropertyValue,IsNillable" + }; + + // Get all Excel files in the folder + string[] workbookFiles = Directory.GetFiles(folderPath, "*.xlsx", SearchOption.TopDirectoryOnly); + + foreach (string filePath in workbookFiles) + { + // Ensure the file still exists before attempting to load + if (!File.Exists(filePath)) + continue; + + try + { + // Load the workbook (no password; if required, the exception will be caught) + using (Workbook workbook = new Workbook(filePath)) + { + // Access the collection of ContentTypeProperty objects + ContentTypePropertyCollection ctProps = workbook.ContentTypeProperties; + + // Iterate through each property + for (int i = 0; i < ctProps.Count; i++) + { + ContentTypeProperty prop = ctProps[i]; + + // If IsNillable is false, consider it "lacking the IsNillable flag" + if (!prop.IsNillable) + { + string line = string.Format( + "\"{0}\",\"{1}\",\"{2}\",\"{3}\",{4}", + Path.GetFileName(filePath), + prop.Name, + prop.Type, + prop.Value?.Replace("\"", "\"\""), + prop.IsNillable); + + reportLines.Add(line); + } + } + } + } + catch (CellsException ex) + { + // Detect password‑protected files via message content + if (ex.Message != null && ex.Message.IndexOf("password", StringComparison.OrdinalIgnoreCase) >= 0) + { + Console.WriteLine($"Skipped password‑protected workbook: {Path.GetFileName(filePath)}"); + } + else + { + Console.WriteLine($"CellsException processing '{Path.GetFileName(filePath)}': {ex.Message}"); + } + } + catch (Exception ex) + { + // Handle other unexpected errors gracefully + Console.WriteLine($"Error processing '{Path.GetFileName(filePath)}': {ex.Message}"); + } + } + + // Ensure the output directory exists + string? reportDir = Path.GetDirectoryName(reportPath); + if (!string.IsNullOrEmpty(reportDir)) + { + Directory.CreateDirectory(reportDir); + } + + // Write all lines to the CSV file + File.WriteAllLines(reportPath, reportLines); + + Console.WriteLine("Report generated at: " + reportPath); + } + catch (Exception ex) + { + // Top‑level safety net + Console.WriteLine("Fatal error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/manage-workbook/implement-a-commandline-tool-that-accepts-a-file-path-adds-an-optional-property-and-disposes-the-workbook.cs b/manage-workbook/implement-a-commandline-tool-that-accepts-a-file-path-adds-an-optional-property-and-disposes-the-workbook.cs new file mode 100644 index 0000000000..b7fbb47743 --- /dev/null +++ b/manage-workbook/implement-a-commandline-tool-that-accepts-a-file-path-adds-an-optional-property-and-disposes-the-workbook.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsCommandLineTool +{ + class Program + { + // Entry point of the command‑line application + static void Main(string[] args) + { + // Expect at least one argument: the path to the Excel file + if (args.Length == 0) + { + Console.WriteLine("Usage: AsposeCellsCommandLineTool [propertyName propertyValue]"); + return; + } + + string filePath = args[0]; + + // Validate that the file exists before attempting to load it + if (!System.IO.File.Exists(filePath)) + { + Console.WriteLine($"Error: File not found - {filePath}"); + return; + } + + // Load the workbook using the string constructor (load rule) + Workbook workbook = new Workbook(filePath); + + // If a property name and value are supplied, add a custom document property + if (args.Length >= 3) + { + string propName = args[1]; + string propValue = args[2]; + + // Add the custom property (no specific rule exists for this operation) + workbook.CustomDocumentProperties.Add(propName, propValue); + + // Save the workbook back to the same file (save rule) + workbook.Save(filePath); + Console.WriteLine($"Added custom property '{propName}' with value '{propValue}' and saved workbook."); + } + else + { + Console.WriteLine("No custom property specified. Workbook loaded and will be disposed."); + } + + // Dispose the workbook to release unmanaged resources (dispose rule) + workbook.Dispose(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/implement-error-handling-to-continue-batch-processing-when-a-workbook-fails-to-load-due-to-corruption.cs b/manage-workbook/implement-error-handling-to-continue-batch-processing-when-a-workbook-fails-to-load-due-to-corruption.cs new file mode 100644 index 0000000000..a28c3eb052 --- /dev/null +++ b/manage-workbook/implement-error-handling-to-continue-batch-processing-when-a-workbook-fails-to-load-due-to-corruption.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; + +class BatchProcessor +{ + // Processes a collection of Excel files. + // If a file is corrupted, it logs the error and continues with the next file. + public static void ProcessWorkbooks(IEnumerable filePaths) + { + foreach (var path in filePaths) + { + try + { + // Load the workbook. Aspose.Cells will attempt to open the file. + Workbook workbook = new Workbook(path); + + // Indicate that the workbook was opened in repair mode (safe mode). + workbook.Settings.RepairLoad = true; + + // Example processing: calculate all formulas. + workbook.CalculateFormula(); + + // Save the processed workbook to an output folder. + string outputFolder = "Processed"; + System.IO.Directory.CreateDirectory(outputFolder); + string outputPath = System.IO.Path.Combine(outputFolder, System.IO.Path.GetFileName(path)); + workbook.Save(outputPath); + + Console.WriteLine($"Successfully processed and saved: {outputPath}"); + } + catch (CellsException ex) when (ex.Code == ExceptionType.FileCorrupted) + { + // Handle corrupted file without stopping the batch. + Console.WriteLine($"Skipped corrupted file '{path}': {ex.Message}"); + } + catch (Exception ex) + { + // Handle any other unexpected errors. + Console.WriteLine($"Error processing '{path}': {ex.Message}"); + } + } + } + + static void Main() + { + // Example list of workbook file paths to process. + var files = new List + { + "Workbook1.xlsx", + "CorruptedWorkbook.xlsx", + "Workbook2.xlsx" + }; + + ProcessWorkbooks(files); + } +} \ No newline at end of file diff --git a/manage-workbook/insert-a-hyperlink-into-a-cell-that-points-to-an-external-website-and-opens-in-a-new-tab.cs b/manage-workbook/insert-a-hyperlink-into-a-cell-that-points-to-an-external-website-and-opens-in-a-new-tab.cs new file mode 100644 index 0000000000..2fbe0b22da --- /dev/null +++ b/manage-workbook/insert-a-hyperlink-into-a-cell-that-points-to-an-external-website-and-opens-in-a-new-tab.cs @@ -0,0 +1,30 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Drawing; + +namespace HyperlinkExample +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Add a hyperlink to cell A1 that points to an external website + // Parameters: cell name, rows, columns, address + int linkIndex = worksheet.Hyperlinks.Add("A1", 1, 1, "https://www.example.com"); + + // Set the display text for the hyperlink (optional) + worksheet.Hyperlinks[linkIndex].TextToDisplay = "Visit Example.com"; + + // When saving to HTML, set the link target type to open in a new tab/window + HtmlSaveOptions saveOptions = new HtmlSaveOptions(); + saveOptions.LinkTargetType = HtmlLinkTargetType.Blank; // "_blank" target + + // Save the workbook as an HTML file; the hyperlink will open in a new tab + workbook.Save("HyperlinkExample.html", saveOptions); + } + } +} \ No newline at end of file diff --git a/manage-workbook/integrate-workbook-disposal-into-a-finally-block-to-guarantee-resource-release-even-when-exceptions-occur.cs b/manage-workbook/integrate-workbook-disposal-into-a-finally-block-to-guarantee-resource-release-even-when-exceptions-occur.cs new file mode 100644 index 0000000000..7d8cb48368 --- /dev/null +++ b/manage-workbook/integrate-workbook-disposal-into-a-finally-block-to-guarantee-resource-release-even-when-exceptions-occur.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsDisposeExample +{ + class Program + { + static void Main() + { + Workbook workbook = null; + try + { + // Create a new workbook instance (rule: Workbook constructor) + workbook = new Workbook(); + + // Access the default worksheet and add some data + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Hello, Aspose.Cells!"); + sheet.Cells["B1"].PutValue(DateTime.Now); + + // Save the workbook to disk (rule: Save(string)) + workbook.Save("DisposedWorkbook.xlsx"); + } + catch (Exception ex) + { + // Handle any errors that occur during processing + Console.WriteLine($"Error: {ex.Message}"); + } + finally + { + // Ensure the workbook is disposed even if an exception occurs (rule: Workbook.Dispose) + workbook?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/iterate-through-multiple-workbooks-in-a-directory-adding-a-shared-contenttypeproperty-to-each-file.cs b/manage-workbook/iterate-through-multiple-workbooks-in-a-directory-adding-a-shared-contenttypeproperty-to-each-file.cs new file mode 100644 index 0000000000..680fc849ea --- /dev/null +++ b/manage-workbook/iterate-through-multiple-workbooks-in-a-directory-adding-a-shared-contenttypeproperty-to-each-file.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsBatchProcessing +{ + class Program + { + static void Main(string[] args) + { + try + { + // Directory containing the Excel workbooks + string folderPath = @"C:\Workbooks"; + + // Verify the directory exists + if (!Directory.Exists(folderPath)) + { + Console.WriteLine($"Folder not found: {folderPath}"); + return; + } + + // Define the shared content type property name and value + const string propertyName = "SharedProperty"; + const string propertyValue = "SharedValue"; + + // Get all Excel files in the directory + string[] files = Directory.GetFiles(folderPath, "*.xlsx"); + + foreach (string filePath in files) + { + // Ensure the file still exists before processing + if (!File.Exists(filePath)) + { + Console.WriteLine($"File not found: {filePath}"); + continue; + } + + try + { + // Load the workbook (will throw if the file is password‑protected) + Workbook workbook = new Workbook(filePath); + + // Add the shared content type property + workbook.ContentTypeProperties.Add(propertyName, propertyValue); + + // Overwrite the original file + workbook.Save(filePath); + + Console.WriteLine($"Processed: {Path.GetFileName(filePath)}"); + } + catch (Exception ex) + { + // Detect password‑protected files by message content + if (ex.Message != null && ex.Message.IndexOf("password", StringComparison.OrdinalIgnoreCase) >= 0) + { + Console.WriteLine($"Skipped password‑protected file: {Path.GetFileName(filePath)}"); + } + else + { + Console.WriteLine($"Error processing {Path.GetFileName(filePath)}: {ex.Message}"); + } + } + } + + Console.WriteLine("Content type property added to all applicable workbooks."); + } + catch (Exception ex) + { + // Catch any unexpected errors in the overall process + Console.WriteLine($"Fatal error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/load-a-csv-file-into-a-workbook-specify-the-delimiter-and-treat-the-first-row-as-headers.cs b/manage-workbook/load-a-csv-file-into-a-workbook-specify-the-delimiter-and-treat-the-first-row-as-headers.cs new file mode 100644 index 0000000000..74bd86116e --- /dev/null +++ b/manage-workbook/load-a-csv-file-into-a-workbook-specify-the-delimiter-and-treat-the-first-row-as-headers.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; + +class LoadCsvWithHeaders +{ + static void Main() + { + // Path to the CSV file to be loaded + string csvPath = "input.csv"; + + // Create TxtLoadOptions for CSV format + TxtLoadOptions loadOptions = new TxtLoadOptions(LoadFormat.Csv); + // Specify the delimiter (e.g., comma) + loadOptions.Separator = ','; + // Treat the first row as header rows + loadOptions.HeaderRowsCount = 1; + // Optional: convert numeric strings to numeric cell types + loadOptions.ConvertNumericData = true; + + // Load the CSV file into a workbook using the configured options + Workbook workbook = new Workbook(csvPath, loadOptions); + + // Access the first worksheet (optional demonstration) + Worksheet sheet = workbook.Worksheets[0]; + // Example: display the value of the first data cell (A2) after the header + Console.WriteLine("First data cell (A2): " + sheet.Cells["A2"].StringValue); + + // Save the workbook to an Excel file + workbook.Save("output.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/manage-workbook/load-a-workbook-from-a-memory-stream-modify-a-cell-value-and-write-back-to-the-stream.cs b/manage-workbook/load-a-workbook-from-a-memory-stream-modify-a-cell-value-and-write-back-to-the-stream.cs new file mode 100644 index 0000000000..dac9a77bc2 --- /dev/null +++ b/manage-workbook/load-a-workbook-from-a-memory-stream-modify-a-cell-value-and-write-back-to-the-stream.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // ---------- Create a new workbook ---------- + Workbook workbook = new Workbook(); + // Add initial data to cell A1 + workbook.Worksheets[0].Cells["A1"].PutValue("Original Value"); + + // ---------- Save the workbook to a memory stream ---------- + // This uses the provided SaveToStream method (returns a MemoryStream) + MemoryStream memoryStream = workbook.SaveToStream(); + + // Reset the stream position to the beginning before loading + memoryStream.Position = 0; + + // ---------- Load the workbook from the memory stream ---------- + // Uses the Workbook(Stream) constructor as per the provided rule + Workbook loadedWorkbook = new Workbook(memoryStream); + + // ---------- Modify a cell value ---------- + loadedWorkbook.Worksheets[0].Cells["A1"].PutValue("Modified Value"); + + // ---------- Save the modified workbook back to a new memory stream ---------- + MemoryStream resultStream = loadedWorkbook.SaveToStream(); + + // Optional: write the result stream to a file for verification + using (FileStream file = new FileStream("ModifiedResult.xls", FileMode.Create, FileAccess.Write)) + { + resultStream.WriteTo(file); + } + + // Clean up streams + memoryStream.Dispose(); + resultStream.Dispose(); + } +} \ No newline at end of file diff --git a/manage-workbook/load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs b/manage-workbook/load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs new file mode 100644 index 0000000000..a657edb9d5 --- /dev/null +++ b/manage-workbook/load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class RemoveUnusedStylesDemo + { + public static void Main(string[] args) + { + Run(); + } + + public static void Run() + { + try + { + // Path to the workbook that contains many unused styles + string inputPath = "InputWithUnusedStyles.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 from the file path + Workbook wb = new Workbook(inputPath); + + // Show the number of styles before removal + Console.WriteLine($"Styles before cleaning: {wb.CountOfStylesInPool}"); + + // Remove all unused styles + wb.RemoveUnusedStyles(); + + // Show the number of styles after removal + Console.WriteLine($"Styles after cleaning: {wb.CountOfStylesInPool}"); + + // Save the cleaned workbook + string outputPath = "CleanedWorkbook.xlsx"; + wb.Save(outputPath); + + Console.WriteLine($"Cleaned workbook saved to: {outputPath}"); + } + catch (Exception ex) + { + // Log any unexpected errors + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/load-an-xlsx-workbook-from-a-file-stream-and-enable-automatic-formula-calculation.cs b/manage-workbook/load-an-xlsx-workbook-from-a-file-stream-and-enable-automatic-formula-calculation.cs new file mode 100644 index 0000000000..83852c9a03 --- /dev/null +++ b/manage-workbook/load-an-xlsx-workbook-from-a-file-stream-and-enable-automatic-formula-calculation.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsLoadAndCalculate +{ + class Program + { + static void Main() + { + // Path to the source XLSX file + string inputPath = "input.xlsx"; + + // Open the file as a read‑only stream + using (FileStream stream = new FileStream(inputPath, FileMode.Open, FileAccess.Read)) + { + // Create load options (default settings) + LoadOptions loadOptions = new LoadOptions(); + + // Load the workbook from the stream using the constructor that accepts a Stream and LoadOptions + Workbook workbook = new Workbook(stream, loadOptions); + + // Enable automatic formula calculation by setting the calculation mode to Automatic + workbook.Settings.FormulaSettings.CalculationMode = CalcModeType.Automatic; + + // (Optional) Force calculation now if you need the results immediately + // workbook.CalculateFormula(); + + // Example: read a calculated cell value after enabling automatic calculation + Worksheet sheet = workbook.Worksheets[0]; + Console.WriteLine("Value of A1 after loading: " + sheet.Cells["A1"].Value); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/log-the-duration-of-each-workbooks-processing-steps-to-identify-performance-bottlenecks.cs b/manage-workbook/log-the-duration-of-each-workbooks-processing-steps-to-identify-performance-bottlenecks.cs new file mode 100644 index 0000000000..52a0840161 --- /dev/null +++ b/manage-workbook/log-the-duration-of-each-workbooks-processing-steps-to-identify-performance-bottlenecks.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsPerformanceLogging +{ + class Program + { + static void Main() + { + // List of workbook file paths to process + List files = new List + { + "Input1.xlsx", + "Input2.xlsx", + // Add more file paths as needed + }; + + foreach (string filePath in files) + { + Console.WriteLine($"--- Processing workbook: {filePath} ---"); + + // Verify that the input file exists + if (!File.Exists(filePath)) + { + Console.WriteLine($"Error: File not found – {filePath}"); + Console.WriteLine(); + continue; + } + + try + { + // Stopwatch to measure total processing time + Stopwatch totalStopwatch = Stopwatch.StartNew(); + + // 1. Load workbook + Stopwatch loadStopwatch = Stopwatch.StartNew(); + Workbook wb = new Workbook(filePath); + loadStopwatch.Stop(); + Console.WriteLine($"Load time: {loadStopwatch.ElapsedMilliseconds} ms"); + + // 2. Calculate formulas (if any) + Stopwatch calcStopwatch = Stopwatch.StartNew(); + wb.CalculateFormula(); + calcStopwatch.Stop(); + Console.WriteLine($"Formula calculation time: {calcStopwatch.ElapsedMilliseconds} ms"); + + // 3. Prepare output path and ensure directory exists + string outputDirectory = Path.GetDirectoryName(filePath) ?? string.Empty; + string outputPath = Path.Combine( + outputDirectory, + Path.GetFileNameWithoutExtension(filePath) + "_Processed.xlsx"); + + if (!Directory.Exists(outputDirectory)) + { + Directory.CreateDirectory(outputDirectory); + } + + // 4. Save workbook + Stopwatch saveStopwatch = Stopwatch.StartNew(); + wb.Save(outputPath); + saveStopwatch.Stop(); + Console.WriteLine($"Save time: {saveStopwatch.ElapsedMilliseconds} ms"); + + // 5. Total time + totalStopwatch.Stop(); + Console.WriteLine($"Total processing time: {totalStopwatch.ElapsedMilliseconds} ms"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred while processing {filePath}: {ex.Message}"); + } + + Console.WriteLine(); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/mark-the-newly-added-projectid-property-as-optional-by-setting-its-isnillable-flag-to-true.cs b/manage-workbook/mark-the-newly-added-projectid-property-as-optional-by-setting-its-isnillable-flag-to-true.cs new file mode 100644 index 0000000000..192ede464a --- /dev/null +++ b/manage-workbook/mark-the-newly-added-projectid-property-as-optional-by-setting-its-isnillable-flag-to-true.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +namespace AsposeCellsProjectIdExample +{ + class Program + { + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Add the new ProjectId content type property (value and type can be set as needed) + // Here we add it with a placeholder value and type "string" + workbook.ContentTypeProperties.Add("ProjectId", "12345", "string"); + + // Retrieve the added property + ContentTypeProperty projectIdProperty = workbook.ContentTypeProperties["ProjectId"]; + + // Mark the property as optional by setting IsNillable to true + projectIdProperty.IsNillable = true; + + // Optional: output the flag to verify + Console.WriteLine($"ProjectId IsNillable: {projectIdProperty.IsNillable}"); + + // Save the workbook to a file + workbook.Save("ProjectIdOptionalDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/measure-the-file-size-before-and-after-removing-unused-styles-to-assess-reduction-impact.cs b/manage-workbook/measure-the-file-size-before-and-after-removing-unused-styles-to-assess-reduction-impact.cs new file mode 100644 index 0000000000..29f11952d7 --- /dev/null +++ b/manage-workbook/measure-the-file-size-before-and-after-removing-unused-styles-to-assess-reduction-impact.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsStyleSizeDemo +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Access the first worksheet + Worksheet sheet = wb.Worksheets[0]; + + // Add sample data with different styles + for (int i = 0; i < 10; i++) + { + Cell cell = sheet.Cells[i, 0]; + cell.PutValue("Item " + (i + 1)); + + // Create a unique style for each cell + Style style = wb.CreateStyle(); + style.Font.Name = "Arial"; + style.Font.Size = 10 + i; + style.Font.IsBold = i % 2 == 0; + cell.SetStyle(style); + } + + // Delete some rows to create unused styles + sheet.Cells.DeleteRows(5, 5); + + // Save workbook before removing unused styles + string beforePath = "BeforeRemoveUnusedStyles.xlsx"; + wb.Save(beforePath); + + // Measure file size before removal + long sizeBefore = new FileInfo(beforePath).Length; + + // Remove all unused styles + wb.RemoveUnusedStyles(); + + // Save workbook after removing unused styles + string afterPath = "AfterRemoveUnusedStyles.xlsx"; + wb.Save(afterPath); + + // Measure file size after removal + long sizeAfter = new FileInfo(afterPath).Length; + + // Output the results + Console.WriteLine($"File size before removing unused styles: {sizeBefore} bytes"); + Console.WriteLine($"File size after removing unused styles: {sizeAfter} bytes"); + Console.WriteLine($"Size reduction: {sizeBefore - sizeAfter} bytes"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/merge-cells-in-a-header-row-apply-bold-font-and-center-the-text-horizontally.cs b/manage-workbook/merge-cells-in-a-header-row-apply-bold-font-and-center-the-text-horizontally.cs new file mode 100644 index 0000000000..ca8eda4be7 --- /dev/null +++ b/manage-workbook/merge-cells-in-a-header-row-apply-bold-font-and-center-the-text-horizontally.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsHeaderMergeDemo +{ + 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; + + // Merge cells in the first row (A1:D1) to create a header area + // Parameters: firstRow, firstColumn, totalRows, totalColumns + cells.Merge(0, 0, 1, 4); + + // Set the header text in the merged cell (upper‑left cell of the range) + cells[0, 0].PutValue("Report Header"); + + // Retrieve the style of the merged cell + Style headerStyle = cells[0, 0].GetStyle(); + + // Apply bold font + headerStyle.Font.IsBold = true; + + // Center the text horizontally + headerStyle.HorizontalAlignment = TextAlignmentType.Center; + + // Apply the modified style back to the merged cell + cells[0, 0].SetStyle(headerStyle); + + // Save the workbook to a file + workbook.Save("HeaderMerged.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/move-a-worksheet-to-a-new-position-within-the-same-workbook-and-update-its-tab-color.cs b/manage-workbook/move-a-worksheet-to-a-new-position-within-the-same-workbook-and-update-its-tab-color.cs new file mode 100644 index 0000000000..fb0a4bf165 --- /dev/null +++ b/manage-workbook/move-a-worksheet-to-a-new-position-within-the-same-workbook-and-update-its-tab-color.cs @@ -0,0 +1,29 @@ +using System; +using System.Drawing; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook (lifecycle create) + Workbook workbook = new Workbook(); + + // Add sample worksheets + workbook.Worksheets.Add("SheetA"); + workbook.Worksheets.Add("SheetB"); + workbook.Worksheets.Add("SheetC"); + + // Select the worksheet to move (e.g., "SheetC") + Worksheet sheetToMove = workbook.Worksheets["SheetC"]; + + // Move the worksheet to the desired index (e.g., position 1) + sheetToMove.MoveTo(1); // Moves "SheetC" to be the second tab + + // Update the tab color of the moved worksheet + sheetToMove.TabColor = Color.LightBlue; + + // Save the workbook (lifecycle save) + workbook.Save("MovedAndColoredSheet.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/open-the-saved-xlsx-file-as-a-zip-archive-and-verify-the-presence-of-the-customxml-folder.cs b/manage-workbook/open-the-saved-xlsx-file-as-a-zip-archive-and-verify-the-presence-of-the-customxml-folder.cs new file mode 100644 index 0000000000..26f995406b --- /dev/null +++ b/manage-workbook/open-the-saved-xlsx-file-as-a-zip-archive-and-verify-the-presence-of-the-customxml-folder.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Cells; + +namespace AsposeCellsCustomXmlCheck +{ + class Program + { + static void Main() + { + // Path to the Excel file that should contain custom XML parts + string excelPath = "output.xlsx"; + + // ----------------------------------------------------------------- + // Load the workbook (using Aspose.Cells lifecycle rule) + // ----------------------------------------------------------------- + Workbook workbook = new Workbook(excelPath); + + // (Optional) Add a custom XML part if you want to ensure the folder exists + // This demonstrates the creation of a custom XML part. + // Comment out if the file already contains custom XML. + /* + string xmlData = ""; + string xmlSchema = "" + + "" + + "" + + ""; + workbook.CustomXmlParts.Add(System.Text.Encoding.UTF8.GetBytes(xmlData), + System.Text.Encoding.UTF8.GetBytes(xmlSchema)); + workbook.Save(excelPath); + */ + + // ----------------------------------------------------------------- + // Open the saved .xlsx file as a zip archive + // ----------------------------------------------------------------- + using (FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read)) + using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read, leaveOpen: false)) + { + // Verify the presence of the "customXml" folder + bool customXmlFolderExists = false; + + foreach (ZipArchiveEntry entry in zip.Entries) + { + // In a zip archive, a folder is represented by an entry whose name ends with '/' + // We check for any entry that starts with "customXml/" (case‑insensitive) + if (entry.FullName.StartsWith("customXml/", StringComparison.OrdinalIgnoreCase)) + { + customXmlFolderExists = true; + break; + } + } + + Console.WriteLine($"customXml folder present: {customXmlFolderExists}"); + } + } + } +} \ No newline at end of file diff --git a/manage-workbook/protect-the-workbook-with-a-password-and-allow-only-readonly-access-for-users.cs b/manage-workbook/protect-the-workbook-with-a-password-and-allow-only-readonly-access-for-users.cs new file mode 100644 index 0000000000..a7a32e4c19 --- /dev/null +++ b/manage-workbook/protect-the-workbook-with-a-password-and-allow-only-readonly-access-for-users.cs @@ -0,0 +1,22 @@ +using Aspose.Cells; + +class ProtectWorkbookReadOnly +{ + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Set the password required to modify the file + wb.Settings.WriteProtection.Password = "modifyPwd"; + + // Recommend opening the file as read‑only + wb.Settings.WriteProtection.RecommendReadOnly = true; + + // Optional: set the author of the protection + wb.Settings.WriteProtection.Author = "Admin"; + + // Save the protected workbook + wb.Save("ReadOnlyProtectedWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/read-the-optional-flag-of-each-contenttypeproperty-and-generate-a-summary-indicating-which-are-nillable.cs b/manage-workbook/read-the-optional-flag-of-each-contenttypeproperty-and-generate-a-summary-indicating-which-are-nillable.cs new file mode 100644 index 0000000000..78b7974ecc --- /dev/null +++ b/manage-workbook/read-the-optional-flag-of-each-contenttypeproperty-and-generate-a-summary-indicating-which-are-nillable.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +class ContentTypePropertyNillableSummary +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add sample content type properties with different IsNillable settings + int idx1 = workbook.ContentTypeProperties.Add("PropA", "ValueA", "text"); + workbook.ContentTypeProperties[idx1].IsNillable = true; + + int idx2 = workbook.ContentTypeProperties.Add("PropB", "123", "number"); + workbook.ContentTypeProperties[idx2].IsNillable = false; + + int idx3 = workbook.ContentTypeProperties.Add("PropC", "", "string"); + workbook.ContentTypeProperties[idx3].IsNillable = true; + + // Generate a summary indicating which properties are nillable + Console.WriteLine("ContentTypeProperty Nillable Summary:"); + foreach (ContentTypeProperty prop in workbook.ContentTypeProperties) + { + string status = prop.IsNillable ? "Nillable" : "Not Nillable"; + Console.WriteLine($"- {prop.Name}: {status}"); + } + + // Save the workbook (optional) + workbook.Save("ContentTypePropertiesSummary.xlsx"); + } +} \ No newline at end of file diff --git a/manage-workbook/replace-all-occurrences-of-a-placeholder-string-using-a-regular-expression-across-the-entire-workbook.cs b/manage-workbook/replace-all-occurrences-of-a-placeholder-string-using-a-regular-expression-across-the-entire-workbook.cs new file mode 100644 index 0000000000..238b493b80 --- /dev/null +++ b/manage-workbook/replace-all-occurrences-of-a-placeholder-string-using-a-regular-expression-across-the-entire-workbook.cs @@ -0,0 +1,43 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsReplaceRegexDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (or load an existing one) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Populate some cells with data that matches the regex pattern + sheet.Cells["A1"].PutValue("Item-001"); + sheet.Cells["A2"].PutValue("Item-002"); + sheet.Cells["A3"].PutValue("Product-ABC"); + sheet.Cells["A4"].PutValue("Item-003"); + + // Define the regular expression pattern to find all strings starting with "Item-" + string regexPattern = @"Item-\d{3}"; + // Define the replacement text + string replacement = "ReplacedItem"; + + // Configure replace options to treat the search key as a regular expression + ReplaceOptions options = new ReplaceOptions + { + RegexKey = true, // Enable regex matching + CaseSensitive = false, // Case-insensitive matching + MatchEntireCellContents = false // Allow partial matches within cell contents + }; + + // Perform the replacement across the entire workbook + int replacedCount = workbook.Replace(regexPattern, replacement, options); + Console.WriteLine($"Total replacements made: {replacedCount}"); + + // Save the workbook to a file + workbook.Save("RegexReplaceResult.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/search-for-dates-matching-a-pattern-and-reformat-them-to-iso-8601-using-regex-replacement.cs b/manage-workbook/search-for-dates-matching-a-pattern-and-reformat-them-to-iso-8601-using-regex-replacement.cs new file mode 100644 index 0000000000..f558d9b2cf --- /dev/null +++ b/manage-workbook/search-for-dates-matching-a-pattern-and-reformat-them-to-iso-8601-using-regex-replacement.cs @@ -0,0 +1,45 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsDateRegexReplace +{ + class Program + { + static void Main() + { + // Create a new workbook (lifecycle rule: create) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Sample data containing dates in MM/dd/yyyy format + cells["A1"].PutValue("Report date: 12/31/2022"); + cells["A2"].PutValue("Start: 01/15/2023 End: 02/20/2023"); + cells["A3"].PutValue("No date here"); + cells["A4"].PutValue("Another date 07/04/2021"); + + // Define a regex pattern that matches dates in MM/dd/yyyy + string datePattern = @"(\d{2})/(\d{2})/(\d{4})"; + + // Replacement string to convert to ISO 8601 (yyyy-MM-dd) + // $1 = month, $2 = day, $3 = year + string isoReplacement = "$3-$1-$2"; + + // Configure replace options to treat the pattern as a regular expression + ReplaceOptions options = new ReplaceOptions + { + RegexKey = true, // Enable regex matching + CaseSensitive = false, // Not relevant for dates but keep default + MatchEntireCellContents = false // Replace dates within larger strings + }; + + // Perform the replacement across the entire workbook (lifecycle rule: replace) + workbook.Replace(datePattern, isoReplacement, options); + + // Save the workbook (lifecycle rule: save) + workbook.Save("DateRegexReplaced.xlsx"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/serialize-the-workbooks-custom-xml-part-to-a-string-and-log-its-xml-content-for-debugging.cs b/manage-workbook/serialize-the-workbooks-custom-xml-part-to-a-string-and-log-its-xml-content-for-debugging.cs new file mode 100644 index 0000000000..b8c142546e --- /dev/null +++ b/manage-workbook/serialize-the-workbooks-custom-xml-part-to-a-string-and-log-its-xml-content-for-debugging.cs @@ -0,0 +1,26 @@ +using System; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Add a sample custom XML part + string xmlData = "Sample"; + byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlData); + int partIndex = wb.CustomXmlParts.Add(xmlBytes, null); + CustomXmlPart customPart = wb.CustomXmlParts[partIndex]; + + // Serialize the custom XML part to a string + string xmlContent = Encoding.UTF8.GetString(customPart.Data); + + // Log the XML content for debugging + Console.WriteLine("Custom XML Part Content:"); + Console.WriteLine(xmlContent); + } +} \ No newline at end of file diff --git a/manage-workbook/set-isnillable-to-true-for-the-shared-property-across-all-workbooks-to-ensure-optional-metadata.cs b/manage-workbook/set-isnillable-to-true-for-the-shared-property-across-all-workbooks-to-ensure-optional-metadata.cs new file mode 100644 index 0000000000..066b847829 --- /dev/null +++ b/manage-workbook/set-isnillable-to-true-for-the-shared-property-across-all-workbooks-to-ensure-optional-metadata.cs @@ -0,0 +1,29 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Properties; + +class SetIsNillableForSharedProperty +{ + static void Main() + { + // Paths of the workbooks to be processed + string[] workbookFiles = { "Workbook1.xlsx", "Workbook2.xlsx", "Workbook3.xlsx" }; + + foreach (string filePath in workbookFiles) + { + // Load the existing workbook + Workbook workbook = new Workbook(filePath); + + // Add (or overwrite) a content type property named "Shared" + // The value and type are arbitrary; the key part is setting IsNillable + int propIndex = workbook.ContentTypeProperties.Add("Shared", "Aspose", "text"); + + // Retrieve the newly added property and mark it as nillable (optional) + ContentTypeProperty sharedProperty = workbook.ContentTypeProperties[propIndex]; + sharedProperty.IsNillable = true; + + // Save the workbook with the updated metadata + workbook.Save(filePath); + } + } +} \ No newline at end of file diff --git a/manage-workbook/set-page-margins-to-narrow-values-and-configure-the-workbook-to-print-in-landscape-orientation.cs b/manage-workbook/set-page-margins-to-narrow-values-and-configure-the-workbook-to-print-in-landscape-orientation.cs new file mode 100644 index 0000000000..faf804e9e1 --- /dev/null +++ b/manage-workbook/set-page-margins-to-narrow-values-and-configure-the-workbook-to-print-in-landscape-orientation.cs @@ -0,0 +1,37 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsPageSetupDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (lifecycle create rule) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Set narrow page margins (values in centimeters) + // Adjust these values as needed for "narrow" margins + sheet.PageSetup.TopMargin = 0.5; // 0.5 cm top margin + sheet.PageSetup.BottomMargin = 0.5; // 0.5 cm bottom margin + sheet.PageSetup.LeftMargin = 0.5; // 0.5 cm left margin + sheet.PageSetup.RightMargin = 0.5; // 0.5 cm right margin + + // Configure the worksheet to print in landscape orientation + sheet.PageSetup.Orientation = PageOrientationType.Landscape; + + // Add some sample data to visualize the effect + sheet.Cells["A1"].PutValue("Landscape orientation with narrow margins"); + for (int row = 2; row <= 20; row++) + { + sheet.Cells[$"A{row}"].PutValue($"Row {row - 1}"); + } + + // Save the workbook (lifecycle save rule) + workbook.Save("NarrowMarginsLandscape.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/manage-workbook/set-workbook-calculation-engine-to-use-multithreaded-processing-for-faster-evaluation-of-large-data-sets.cs b/manage-workbook/set-workbook-calculation-engine-to-use-multithreaded-processing-for-faster-evaluation-of-large-data-sets.cs new file mode 100644 index 0000000000..6d213dd204 --- /dev/null +++ b/manage-workbook/set-workbook-calculation-engine-to-use-multithreaded-processing-for-faster-evaluation-of-large-data-sets.cs @@ -0,0 +1,52 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsMultiThreadCalculation +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate a large data set with formulas to demonstrate performance + int rows = 5000; + int cols = 10; + + // Fill cells with numeric values + for (int r = 0; r < rows; r++) + { + for (int c = 0; c < cols; c++) + { + cells[r, c].PutValue(r + c); + } + } + + // Add a formula that sums a row – this will be calculated for each row + for (int r = 0; r < rows; r++) + { + // Example: sum of the first 10 columns in the current row + cells[r, cols].Formula = $"=SUM(A{r + 1}:J{r + 1})"; + } + + // Enable multi‑threaded processing for the cells data model. + // This allows Aspose.Cells to evaluate formulas using multiple threads, + // which speeds up calculation on large data sets. + cells.MultiThreadReading = true; + + // Calculate all formulas in the workbook. + // The calculation will take advantage of the multi‑thread setting above. + workbook.CalculateFormula(); + + // Save the workbook to verify the results + workbook.Save("MultiThreadCalculationResult.xlsx", SaveFormat.Xlsx); + + Console.WriteLine("Workbook saved with multi‑threaded calculation enabled."); + } + } +} \ No newline at end of file diff --git a/manage-workbook/set-workbook-theme-to-a-builtin-style-and-update-all-cell-styles-accordingly.cs b/manage-workbook/set-workbook-theme-to-a-builtin-style-and-update-all-cell-styles-accordingly.cs new file mode 100644 index 0000000000..223cb7891a --- /dev/null +++ b/manage-workbook/set-workbook-theme-to-a-builtin-style-and-update-all-cell-styles-accordingly.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsThemeDemo +{ + public class SetBuiltinThemeAndApplyToAllCells + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add sample data to demonstrate the effect + Worksheet ws = workbook.Worksheets[0]; + ws.Cells["A1"].PutValue("Header"); + ws.Cells["A2"].PutValue(123); + ws.Cells["B1"].PutValue(DateTime.Now); + ws.Cells["B2"].PutValue("Sample Text"); + + // Create a built‑in style (e.g., Good) and set it as the workbook's default style + Style builtinStyle = workbook.CreateBuiltinStyle(BuiltinStyleType.Good); + workbook.DefaultStyle = builtinStyle; + + // Apply the default style to every used cell in all worksheets + foreach (Worksheet sheet in workbook.Worksheets) + { + Cells cells = sheet.Cells; + int maxRow = cells.MaxDataRow; + int maxCol = cells.MaxDataColumn; + + for (int row = 0; row <= maxRow; row++) + { + for (int col = 0; col <= maxCol; col++) + { + // Apply only to cells that contain data or have a style + if (cells[row, col].GetStyle() != null) + { + cells[row, col].SetStyle(workbook.DefaultStyle); + } + } + } + } + + // Define output file path + string outputPath = "WorkbookWithBuiltinTheme.xlsx"; + + // Save the workbook + 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 application + public class Program + { + public static void Main(string[] args) + { + SetBuiltinThemeAndApplyToAllCells.Run(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/use-a-memory-stream-to-load-a-workbook-add-metadata-and-save-back-without-touching-the-file-system.cs b/manage-workbook/use-a-memory-stream-to-load-a-workbook-add-metadata-and-save-back-without-touching-the-file-system.cs new file mode 100644 index 0000000000..d7676ddd66 --- /dev/null +++ b/manage-workbook/use-a-memory-stream-to-load-a-workbook-add-metadata-and-save-back-without-touching-the-file-system.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Metadata; + +namespace AsposeCellsMemoryMetadataDemo +{ + class Program + { + static void Main() + { + // 1. Create a new workbook and add some sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample"); + sheet.Cells["B1"].PutValue(123); + + // 2. Save the workbook to a memory stream (XLSX format) + using (MemoryStream workbookStream = new MemoryStream()) + { + workbook.Save(workbookStream, SaveFormat.Xlsx); + workbookStream.Position = 0; // Reset for reading + + // 3. Prepare metadata options for document properties + MetadataOptions metaOptions = new MetadataOptions(MetadataType.DocumentProperties); + + // 4. Load metadata from the workbook stream + WorkbookMetadata metadata = new WorkbookMetadata(workbookStream, metaOptions); + + // 5. Add a custom document property + metadata.CustomDocumentProperties.Add("MyCustomProperty", "CustomValue"); + + // 6. Save the modified metadata to a new memory stream + using (MemoryStream updatedStream = new MemoryStream()) + { + metadata.Save(updatedStream); + updatedStream.Position = 0; // Reset for reading + + // 7. Load a workbook from the updated stream to verify the metadata + Workbook resultWorkbook = new Workbook(updatedStream); + + // 8. Output the custom property value to the console + var prop = resultWorkbook.CustomDocumentProperties["MyCustomProperty"]; + Console.WriteLine($"Custom Property 'MyCustomProperty' = {prop?.Value}"); + } + } + + // Clean up + workbook.Dispose(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/use-workbookloadoptions-to-open-a-passwordprotected-file-then-add-optional-metadata-before-saving.cs b/manage-workbook/use-workbookloadoptions-to-open-a-passwordprotected-file-then-add-optional-metadata-before-saving.cs new file mode 100644 index 0000000000..4c34ddcce4 --- /dev/null +++ b/manage-workbook/use-workbookloadoptions-to-open-a-passwordprotected-file-then-add-optional-metadata-before-saving.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Metadata; + +class Program +{ + static void Main() + { + // Path to the password‑protected workbook + string filePath = "ProtectedWorkbook.xlsx"; + + // Verify that the file exists before attempting to load it + if (!File.Exists(filePath)) + { + Console.WriteLine($"File not found: {filePath}"); + return; + } + + try + { + // Load the workbook with the required password + LoadOptions loadOptions = new LoadOptions + { + Password = "secure123" + }; + Workbook workbook = new Workbook(filePath, loadOptions); + + // (Optional) modify workbook content + workbook.Worksheets[0].Cells["A1"].PutValue("Demo content"); + + // Prepare metadata options for document properties with the same password + MetadataOptions metaOptions = new MetadataOptions(MetadataType.DocumentProperties) + { + Password = "secure123" + }; + + // Load workbook metadata + WorkbookMetadata metadata = new WorkbookMetadata(filePath, metaOptions); + + // Add a custom document property + metadata.CustomDocumentProperties.Add("Project", "AsposeDemo"); + + // Save metadata changes back to the file + metadata.Save(filePath); + + // Save any workbook content changes (overwrites the same file) + workbook.Save(filePath); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/manage-workbook/validate-all-formulas-in-the-workbook-for-errors-and-generate-a-report-of-problematic-cells.cs b/manage-workbook/validate-all-formulas-in-the-workbook-for-errors-and-generate-a-report-of-problematic-cells.cs new file mode 100644 index 0000000000..ff9572d771 --- /dev/null +++ b/manage-workbook/validate-all-formulas-in-the-workbook-for-errors-and-generate-a-report-of-problematic-cells.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; + +class FormulaValidator +{ + static void Main() + { + // Load the workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Collection to store information about cells with formula errors + List errorReport = new List(); + + // Iterate through each worksheet in the workbook + foreach (Worksheet sheet in workbook.Worksheets) + { + Cells cells = sheet.Cells; + + // Determine the used range of the worksheet + int maxRow = cells.MaxDataRow; + int maxCol = cells.MaxDataColumn; + + // Scan every cell within the used range + for (int row = 0; row <= maxRow; row++) + { + for (int col = 0; col <= maxCol; col++) + { + Cell cell = cells[row, col]; + + // Process only cells that contain a formula + if (cell.IsFormula) + { + try + { + // Evaluate the formula; any exception indicates a problem + sheet.CalculateFormula(cell.Formula); + } + catch (Exception ex) + { + // Record the worksheet name, cell address, and error message + errorReport.Add($"{sheet.Name}!{cell.Name}: {ex.Message}"); + } + } + } + } + } + + // Output the report to a text file + File.WriteAllLines("FormulaErrorsReport.txt", errorReport); + + // Optional console feedback + Console.WriteLine($"Formula validation completed. Problems found: {errorReport.Count}"); + } +} \ No newline at end of file diff --git a/manage-workbook/validate-that-each-saved-workbook-contains-the-expected-custom-xml-part-by-checking-the-zip-entry-name.cs b/manage-workbook/validate-that-each-saved-workbook-contains-the-expected-custom-xml-part-by-checking-the-zip-entry-name.cs new file mode 100644 index 0000000000..1390ccc7a0 --- /dev/null +++ b/manage-workbook/validate-that-each-saved-workbook-contains-the-expected-custom-xml-part-by-checking-the-zip-entry-name.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Text; +using Aspose.Cells; +using Aspose.Cells.Markup; + +namespace AsposeCellsCustomXmlValidation +{ + class Program + { + static void Main() + { + // Path for the workbook file + string workbookPath = "CustomXmlWorkbook.xlsx"; + + // ---------- Create ---------- + // Initialize a new workbook + Workbook wb = new Workbook(); + + // Sample XML data and optional schema + string xmlData = "123"; + byte[] dataBytes = Encoding.UTF8.GetBytes(xmlData); + byte[] schemaBytes = null; // No schema in this example + + // Add the custom XML part to the workbook + // The Add method returns the index of the newly added part + int partIndex = wb.CustomXmlParts.Add(dataBytes, schemaBytes); + + // Optional: set a known ID for later retrieval (not required for zip validation) + wb.CustomXmlParts[partIndex].ID = Guid.NewGuid().ToString(); + + // ---------- Save ---------- + // Save the workbook to disk + wb.Save(workbookPath); + + // ---------- Load ---------- + // Load the workbook back from the saved file + Workbook loadedWb = new Workbook(workbookPath); + + // Verify that the custom XML part exists by inspecting the ZIP package + bool customXmlPartFound = false; + using (FileStream fs = new FileStream(workbookPath, FileMode.Open, FileAccess.Read)) + using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read)) + { + // In OOXML, custom XML parts are stored under the "customXml" folder + foreach (ZipArchiveEntry entry in archive.Entries) + { + if (entry.FullName.StartsWith("customXml/", StringComparison.OrdinalIgnoreCase) && + entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) + { + customXmlPartFound = true; + Console.WriteLine($"Found custom XML part entry: {entry.FullName}"); + break; + } + } + } + + // Output validation result + if (customXmlPartFound) + { + Console.WriteLine("Validation succeeded: Custom XML part is present in the saved workbook."); + } + else + { + Console.WriteLine("Validation failed: Custom XML part is missing in the saved workbook."); + } + + // Clean up (optional) + wb.Dispose(); + loadedWb.Dispose(); + } + } +} \ No newline at end of file diff --git a/manage-workbook/wrap-workbook-loading-and-saving-inside-a-using-statement-to-guarantee-deterministic-disposal-of-resources.cs b/manage-workbook/wrap-workbook-loading-and-saving-inside-a-using-statement-to-guarantee-deterministic-disposal-of-resources.cs new file mode 100644 index 0000000000..05c125fe20 --- /dev/null +++ b/manage-workbook/wrap-workbook-loading-and-saving-inside-a-using-statement-to-guarantee-deterministic-disposal-of-resources.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + public class WorkbookLoadSaveDemo + { + public static void Main(string[] args) + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Prevent FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook inside a using block for deterministic disposal + using (Workbook workbook = new Workbook(inputPath)) + { + // Modify cell A1 + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Modified"); + + // Save the workbook + workbook.Save(outputPath, SaveFormat.Xlsx); + } + + Console.WriteLine($"Workbook saved to {outputPath}"); + } + } +} \ No newline at end of file