diff --git a/index.json b/index.json index 52ddbf847b..f890d3499d 100644 --- a/index.json +++ b/index.json @@ -2174,6 +2174,126 @@ "file": "add-a-custom-property-containing-an-array-of-string-tags-to-categorize-workbook-content.cs", "title": "Add a custom property containing an array of string tags to categorize workbook content." }, + { + "category": "comments-and-notes", + "file": "add-a-threaded-comment-with-multi-line-text-to-cell-h2-and-preserve-line-breaks.cs", + "title": "Add a threaded comment with multi-line text to cell H2 and preserve line breaks." + }, + { + "category": "comments-and-notes", + "file": "apply-a-solid-blue-background-to-a-comment-using-shapefillforecolor-with-the-appropriate-color-code.cs", + "title": "Apply a solid blue background to a comment using Shape.Fill.ForeColor with the appropriate color code." + }, + { + "category": "comments-and-notes", + "file": "batch-process-a-folder-of-workbooks-adding-a-standard-disclaimer-comment-to-each-worksheets-top-left-cell.cs", + "title": "Batch process a folder of workbooks, adding a standard disclaimer comment to each worksheet's top-left cell." + }, + { + "category": "comments-and-notes", + "file": "change-the-font-color-of-a-comment-by-assigning-a-red-value-to-shapetextbodyfontcolor.cs", + "title": "Change the font color of a comment by assigning a red value to Shape.TextBody.Font.Color." + }, + { + "category": "comments-and-notes", + "file": "change-the-font-color-of-comments-in-column-g-to-blue-using-shapetextbodyfontcolor.cs", + "title": "Change the font color of comments in column G to blue using Shape.TextBody.Font.Color." + }, + { + "category": "comments-and-notes", + "file": "copy-a-threaded-comment-from-cell-e5-to-cell-f6-while-preserving-its-author-and-text.cs", + "title": "Copy a threaded comment from cell E5 to cell F6 while preserving its author and text." + }, + { + "category": "comments-and-notes", + "file": "create-a-new-workbook-and-add-a-threaded-comment-to-cell-a1-with-author-john.cs", + "title": "Create a new workbook and add a threaded comment to cell A1 with author John." + }, + { + "category": "comments-and-notes", + "file": "create-a-workbook-add-threaded-comments-to-multiple-cells-and-save-the-file-in-xlsx-format.cs", + "title": "Create a workbook, add threaded comments to multiple cells, and save the file in XLSX format." + }, + { + "category": "comments-and-notes", + "file": "edit-a-specific-threaded-comment-by-setting-its-text-property-to-a-new-string-value.cs", + "title": "Edit a specific threaded comment by setting its Text property to a new string value." + }, + { + "category": "comments-and-notes", + "file": "embed-an-image-as-a-comment-background-by-setting-shapefillpicture-to-a-loaded-picture-object.cs", + "title": "Embed an image as a comment background by setting Shape.Fill.Picture to a loaded picture object." + }, + { + "category": "comments-and-notes", + "file": "iterate-through-a-threadedcommentcollection-to-display-each-comments-text-author-and-creation-timestamp.cs", + "title": "Iterate through a ThreadedCommentCollection to display each comment's text, author, and creation timestamp." + }, + { + "category": "comments-and-notes", + "file": "load-a-workbook-modify-comment-font-colors-based-on-author-and-save-changes-to-a-new-file.cs", + "title": "Load a workbook, modify comment font colors based on author, and save changes to a new file." + }, + { + "category": "comments-and-notes", + "file": "load-an-existing-workbook-retrieve-all-threaded-comments-from-column-b-and-list-their-authors.cs", + "title": "Load an existing workbook, retrieve all threaded comments from column B, and list their authors." + }, + { + "category": "comments-and-notes", + "file": "read-all-threaded-comments-from-a-worksheet-and-count-the-number-of-comments-per-author.cs", + "title": "Read all threaded comments from a worksheet and count the number of comments per author." + }, + { + "category": "comments-and-notes", + "file": "read-the-author-of-each-threaded-comment-in-a-worksheet-and-output-the-list.cs", + "title": "Read the author of each threaded comment in a worksheet and output the list." + }, + { + "category": "comments-and-notes", + "file": "remove-a-threaded-comment-from-cell-c3-using-the-remove-method-on-the-comment-object.cs", + "title": "Remove a threaded comment from cell C3 using the Remove method on the comment object." + }, + { + "category": "comments-and-notes", + "file": "remove-all-comments-older-than-thirty-days-from-a-workbook-based-on-their-createdtime-values.cs", + "title": "Remove all comments older than thirty days from a workbook based on their CreatedTime values." + }, + { + "category": "comments-and-notes", + "file": "retrieve-and-display-the-total-number-of-threaded-comments-present-in-a-workbook.cs", + "title": "Retrieve and display the total number of threaded comments present in a workbook." + }, + { + "category": "comments-and-notes", + "file": "retrieve-the-creation-time-of-a-threaded-comment-via-the-createdtime-property-and-log-it.cs", + "title": "Retrieve the creation time of a threaded comment via the CreatedTime property and log it." + }, + { + "category": "comments-and-notes", + "file": "scan-a-workbook-for-empty-comments-and-remove-them-to-clean-metadata.cs", + "title": "Scan a workbook for empty comments and remove them to clean metadata." + }, + { + "category": "comments-and-notes", + "file": "set-the-text-direction-of-a-comments-shape-to-righttoleft-for-bidirectional-language-support.cs", + "title": "Set the text direction of a comment's shape to RightToLeft for bidirectional language support." + }, + { + "category": "comments-and-notes", + "file": "set-the-text-direction-of-a-comments-shape-to-toptobottom-for-vertical-annotation-layout.cs", + "title": "Set the text direction of a comment's shape to TopToBottom for vertical annotation layout." + }, + { + "category": "comments-and-notes", + "file": "update-the-text-direction-of-all-comments-in-a-worksheet-to-lefttoright-for-standard-layout.cs", + "title": "Update the text direction of all comments in a worksheet to LeftToRight for standard layout." + }, + { + "category": "document-properties", + "file": "add-a-custom-property-containing-an-array-of-string-tags-to-categorize-workbook-content.cs", + "title": "Add a custom property containing an array of string tags to categorize workbook content." + }, { "category": "document-properties", "file": "batch-process-all-workbooks-in-a-folder-setting-each-files-language-property-to-en-gb.cs", @@ -9659,106 +9779,26 @@ "file": "convert-html-tables-with-colspan-and-rowspan-attributes-to-merged-cells-in-the-worksheet.cs", "title": "Convert HTML tables with colspan and rowspan attributes to merged cells in the worksheet." }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-apply-a-custom-theme-based-on-css-variables-defined-in-the-html.cs", - "title": "Convert HTML to Excel and apply a custom theme based on CSS variables defined in the HTML." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-apply-custom-number-formats-for-scientific-notation-values.cs", - "title": "Convert HTML to Excel and apply custom number formats for scientific notation values." - }, { "category": "working-with-html", "file": "convert-html-to-excel-and-apply-date-format-detection-based-on-locale-settings.cs", "title": "Convert HTML to Excel and apply date format detection based on locale settings." }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-embed-custom-document-properties-extracted-from-html-meta-tags.cs", - "title": "Convert HTML to Excel and embed custom document properties extracted from HTML meta tags." - }, { "category": "working-with-html", "file": "convert-html-to-excel-and-encrypt-the-resulting-workbook-with-a-password-for-protection.cs", "title": "Convert HTML to Excel and encrypt the resulting workbook with a password for protection." }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-handle-nested-tables-by-creating-separate-worksheets-for-each-level.cs", - "title": "Convert HTML to Excel and handle nested tables by creating separate worksheets for each level." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-maintain-original-html-page-breaks-as-worksheet-page-breaks.cs", - "title": "Convert HTML to Excel and maintain original HTML page breaks as worksheet page breaks." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-map-css-border-styles-to-excel-cell-border-line-styles.cs", - "title": "Convert HTML to Excel and map CSS border styles to Excel cell border line styles." - }, { "category": "working-with-html", "file": "convert-html-to-excel-and-map-css-text-alignment-to-excel-cell-alignment-properties.cs", "title": "Convert HTML to Excel and map CSS text alignment to Excel cell alignment properties." }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-preserve-cell-comments-as-html-tooltip-attributes.cs", - "title": "Convert HTML to Excel and preserve cell comments as HTML tooltip attributes." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-preserve-conditional-formatting-rules-defined-in-css-classes.cs", - "title": "Convert HTML to Excel and preserve conditional formatting rules defined in CSS classes." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-preserve-hidden-rows-and-columns-indicated-by-css-displaynone.cs", - "title": "Convert HTML to Excel and preserve hidden rows and columns indicated by CSS display:none." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-retain-background-images-by-inserting-them-as-worksheet-background.cs", - "title": "Convert HTML to Excel and retain background images by inserting them as worksheet background." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-retain-embedded-svg-graphics-as-scalable-vector-shapes.cs", - "title": "Convert HTML to Excel and retain embedded SVG graphics as scalable vector shapes." - }, { "category": "working-with-html", "file": "convert-html-to-excel-and-retain-hyperlinks-making-them-clickable-within-the-workbook.cs", "title": "Convert HTML to Excel and retain hyperlinks, making them clickable within the workbook." }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-set-workbook-calculation-mode-to-automatic-for-formula-evaluation.cs", - "title": "Convert HTML to Excel and set workbook calculation mode to automatic for formula evaluation." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-and-set-workbook-culture-to-french-for-proper-decimal-separators.cs", - "title": "Convert HTML to Excel and set workbook culture to French for proper decimal separators." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-asynchronously-and-provide-a-callback-when-conversion-completes.cs", - "title": "Convert HTML to Excel asynchronously and provide a callback when conversion completes." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-in-a-batch-job-processing-a-directory-of-files-into-separate-workbooks.cs", - "title": "Convert HTML to Excel in a batch job processing a directory of files into separate workbooks." - }, - { - "category": "working-with-html", - "file": "convert-html-to-excel-using-a-memory-stream-to-process-large-files-without-temporary-files.cs", - "title": "Convert HTML to Excel using a memory stream to process large files without temporary files." - }, { "category": "working-with-html", "file": "convert-html-to-excel-using-a-stream-provider-that-writes-output-directly-to-cloud-storage.cs", @@ -10109,81 +10149,6 @@ "file": "export-defined-print-area-while-omitting-worksheet-properties-by-combining-exportprintareaonly-and-exportworksheetproperties-false.cs", "title": "Export defined print area while omitting worksheet properties by combining ExportPrintAreaOnly and ExportWorksheetProperties false." }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-add-a-footer-with-page-numbers-generated-by-javascript.cs", - "title": "Export Excel to HTML and add a footer with page numbers generated by JavaScript." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-apply-a-custom-stylesheet-that-overrides-default-cell-colors.cs", - "title": "Export Excel to HTML and apply a custom stylesheet that overrides default cell colors." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-apply-responsive-design-techniques-for-optimal-mobile-device-viewing.cs", - "title": "Export Excel to HTML and apply responsive design techniques for optimal mobile device viewing." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-compress-the-output-html-using-gzip-stream-for-faster-transmission.cs", - "title": "Export Excel to HTML and compress the output HTML using GZIP stream for faster transmission." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-embed-hyperlinks-so-they-remain-functional-in-the-browser.cs", - "title": "Export Excel to HTML and embed hyperlinks so they remain functional in the browser." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-embed-images-as-base64-data-uris-within-the-html-output.cs", - "title": "Export Excel to HTML and embed images as base64 data URIs within the HTML output." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-ensure-formulas-are-displayed-as-values-not-as-formula-strings.cs", - "title": "Export Excel to HTML and ensure formulas are displayed as values, not as formula strings." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-generate-a-separate-css-file-for-styling-instead-of-inline-styles.cs", - "title": "Export Excel to HTML and generate a separate CSS file for styling instead of inline styles." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-include-a-custom-html-header-containing-the-workbook-title.cs", - "title": "Export Excel to HTML and include a custom HTML header containing the workbook title." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-include-custom-metadata-tags-extracted-from-workbook-properties.cs", - "title": "Export Excel to HTML and include custom metadata tags extracted from workbook properties." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-preserve-cell-comments-as-html-tooltip-attributes.cs", - "title": "Export Excel to HTML and preserve cell comments as HTML tooltip attributes." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-preserve-worksheet-gridlines-as-css-border-definitions.cs", - "title": "Export Excel to HTML and preserve worksheet gridlines as CSS border definitions." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-retain-merged-cells-using-appropriate-colspan-and-rowspan-attributes.cs", - "title": "Export Excel to HTML and retain merged cells using appropriate colspan and rowspan attributes." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-and-set-the-output-encoding-to-utf8-for-international-character-support.cs", - "title": "Export Excel to HTML and set the output encoding to UTF\u20118 for international character support." - }, - { - "category": "working-with-html", - "file": "export-excel-to-html-while-preserving-cell-formatting-such-as-font-styles-and-colors.cs", - "title": "Export Excel to HTML while preserving cell formatting such as font styles and colors." - }, { "category": "working-with-html", "file": "export-only-the-defined-print-area-to-html-by-setting-exportprintareaonly-to-true.cs", @@ -10299,11 +10264,6 @@ "file": "load-a-workbook-with-hidden-rows-enable-exportgridlines-and-ensure-hidden-rows-do-not-affect-gridline-rendering.cs", "title": "Load a workbook with hidden rows, enable ExportGridLines, and ensure hidden rows do not affect gridline rendering." }, - { - "category": "working-with-html", - "file": "load-an-excel-workbook-from-a-file-and-export-it-to-html-using-a-custom-stream-provider.cs", - "title": "Load an Excel workbook from a file and export it to HTML using a custom stream provider." - }, { "category": "working-with-html", "file": "load-an-html-file-from-disk-and-convert-it-to-pdf-using-default-options.cs", @@ -11629,6 +11589,11 @@ "file": "add-a-shape-link-it-to-a-cell-with-a-custom-date-format-and-display-formatted-date.cs", "title": "Add a shape, link it to a cell with a custom date format, and display formatted date." }, + { + "category": "working-with-shapes", + "file": "add-a-shape-link-it-to-a-cell-with-a-custom-number-format-including-thousand-separator-and-display.cs", + "title": "Add a shape, link it to a cell with a custom number format including thousand separator, and display." + }, { "category": "working-with-shapes", "file": "add-a-shape-link-it-to-a-cell-with-a-dynamic-named-range-and-verify-shape-updates.cs", @@ -11714,6 +11679,11 @@ "file": "adjust-a-shapes-adjustment-values-to-modify-its-geometry-such-as-changing-a-stars-point-count.cs", "title": "Adjust a shape's adjustment values to modify its geometry, such as changing a star's point count." }, + { + "category": "working-with-shapes", + "file": "adjust-a-shapes-z-order-to-just-above-a-specific-existing-shape.cs", + "title": "Adjust a shape's Z-order to just above a specific existing shape." + }, { "category": "working-with-shapes", "file": "adjust-character-spacing-together-with-line-spacing-to-achieve-balanced-text-appearance.cs", @@ -12694,6 +12664,11 @@ "file": "iterate-through-each-shape-and-use-shapeissmartart-to-identify-smartart-objects.cs", "title": "Iterate through each shape and use Shape.IsSmartArt to identify SmartArt objects." }, + { + "category": "working-with-shapes", + "file": "iterate-worksheets-add-a-shape-to-each-link-to-a-summary-cell-and-log-results.cs", + "title": "Iterate worksheets, add a shape to each, link to a summary cell, and log results." + }, { "category": "working-with-shapes", "file": "link-a-shape-to-a-cell-containing-a-datevalue-function-and-ensure-the-shape-displays-the-formatted-date.cs", @@ -12704,6 +12679,11 @@ "file": "link-a-shape-to-a-cell-containing-a-vlookup-formula-and-ensure-shape-updates-with-lookup-result.cs", "title": "Link a shape to a cell containing a VLOOKUP formula and ensure shape updates with lookup result." }, + { + "category": "working-with-shapes", + "file": "link-a-shape-to-a-cell-that-references-an-external-workbook-and-verify-crossworkbook-content-displays-correctly.cs", + "title": "Link a shape to a cell that references an external workbook and verify cross\u2011workbook content displays correctly." + }, { "category": "working-with-shapes", "file": "link-a-shape-to-a-cell-that-uses-the-char-function-to-display-special-characters-and-verify-rendering.cs", @@ -12944,6 +12924,11 @@ "file": "programmatically-duplicate-a-worksheet-copy-all-shapes-and-maintain-original-z-order-relationships-in-the-copy.cs", "title": "Programmatically duplicate a worksheet, copy all shapes, and maintain original Z-order relationships in the copy." }, + { + "category": "working-with-shapes", + "file": "programmatically-move-a-shape-behind-gridlines-retrieve-its-z-order-and-ensure-the-value-is-negative.cs", + "title": "Programmatically move a shape behind gridlines, retrieve its Z-order, and ensure the value is negative." + }, { "category": "working-with-shapes", "file": "programmatically-move-a-shape-to-the-back-layer-then-adjust-its-absolute-position-to-align-with-a-header.cs", @@ -12994,6 +12979,11 @@ "file": "programmatically-retrieve-a-shapes-absolute-position-add-a-random-offset-and-update-the-shapes-location.cs", "title": "Programmatically retrieve a shape's absolute position, add a random offset, and update the shape's location." }, + { + "category": "working-with-shapes", + "file": "programmatically-retrieve-all-shapes-sort-them-by-z-order-and-output-sorted-list-to-console.cs", + "title": "Programmatically retrieve all shapes, sort them by Z-order, and output sorted list to console." + }, { "category": "working-with-shapes", "file": "programmatically-retrieve-connection-points-of-a-shape-calculate-euclidean-distance-between-first-two-points-and-store-result.cs", diff --git a/manage-workbook/README.md b/manage-workbook/README.md new file mode 100644 index 0000000000..576eb2c3a3 --- /dev/null +++ b/manage-workbook/README.md @@ -0,0 +1,94 @@ +--- +title: Create and Manage Excel Workbooks in C# with Aspose.Cells +description: C# examples for workbook creation, settings, worksheet coordination, custom XML, content-type properties, cleanup, streams, disposal, and batch processing. +product: Aspose.Cells for .NET +category: manage-workbook +language: C# +last_reviewed: 2026-06-29 +--- + +# Create and Manage Excel Workbooks in C# with Aspose.Cells + +Create, configure, inspect, clean, copy, and manage Excel workbooks in C# with Aspose.Cells for .NET. These 60 examples cover workbook lifecycle, settings, worksheet coordination, custom XML parts, content-type properties, unused-style cleanup, streams, disposal, and batch workflows. + +| Fact | Value | +| --- | --- | +| Examples | 60 | +| Primary API | `Workbook` | +| Key collections | `Worksheets`, `CustomXmlParts`, `ContentTypeProperties` | +| Agent guidance | [`AGENTS.md`](AGENTS.md) | + +## Quick answer: How do I create an Excel workbook in C#? + +```csharp +Workbook workbook = new Workbook(); +Worksheet worksheet = workbook.Worksheets[0]; + +worksheet.Name = "Summary"; +worksheet.Cells["A1"].PutValue("Managed workbook"); + +workbook.Save("managed-workbook.xlsx"); +workbook.Dispose(); +``` + +Dispose workbooks deterministically when your application owns them, particularly in batch and stream-processing services. + +## Workbook management map + +| Goal | API/pattern | +| --- | --- | +| Create/configure workbook | `Workbook`, `Workbook.Settings` | +| Coordinate worksheets | `Workbook.Worksheets` | +| Add custom XML | `Workbook.CustomXmlParts` | +| Add content-type properties | `Workbook.ContentTypeProperties` | +| Remove unused styles | `Workbook.RemoveUnusedStyles` | +| Process streams | `Workbook(Stream, ...)` and stream save overloads | +| Release resources | `Dispose` / exception-safe ownership pattern | + +## Featured examples + +- [Copy a worksheet between workbooks](copy-a-worksheet-from-the-source-workbook-to-a-destination-workbook-while-preserving-cell-styles.cs) +- [Add a custom XML part](add-a-custom-xml-part-containing-metadata-and-retrieve-it-later-using-its-unique-identifier.cs) +- [Add a content-type property](add-a-new-contenttypeproperty-named-projectid-with-a-string-value-to-the-workbook.cs) +- [Remove unused workbook styles](load-a-workbook-that-contains-numerous-unused-styles-and-invoke-removeunusedstyles-to-clean-it.cs) +- [Compare file size before and after style cleanup](measure-the-file-size-before-and-after-removing-unused-styles-to-assess-reduction-impact.cs) +- [Load and save through a memory stream](use-a-memory-stream-to-load-a-workbook-add-metadata-and-save-back-without-touching-the-file-system.cs) +- [Guarantee disposal in a finally block](integrate-workbook-disposal-into-a-finally-block-to-guarantee-resource-release-even-when-exceptions-occur.cs) +- [Process 100 workbooks in a batch](create-a-batch-job-that-processes-100-workbooks-adding-optional-metadata-and-removing-unused-styles.cs) + +## FAQ + +### When should a Workbook be disposed? + +Dispose it when the application owns it and all reads/saves are complete. This is especially important for large files and batch processing. + +### Are custom XML parts the same as custom document properties? + +No. Custom XML stores structured XML payloads inside the workbook package. Document properties store metadata name/value pairs. + +### Is removing unused styles always safe? + +Validate before and after output. Compare representative cell styles and rendered appearance because style-cleanup behavior may matter to complex workbooks. + +### How should batch failures be handled? + +Isolate each workbook, continue according to policy, record sanitized diagnostics, avoid input overwrite, and dispose resources after each item. + +## AI retrieval guidance + +Useful intents include "create Excel workbook in C#," "manage workbook settings," "remove unused styles," "add custom XML to XLSX," and "dispose workbook in batch." Distinguish workbook-wide operations from worksheet-only tasks. + +## Related categories and official resources + +- [Open workbook](../open-workbook/) +- [Save workbook](../save-workbook/) +- [Worksheets](../working-with-worksheets/) +- [Document properties](../document-properties/) +- [Workbook API](https://reference.aspose.com/cells/net/aspose.cells/workbook/) +- [Create workbook documentation](https://docs.aspose.com/cells/net/create-new-workbook/) + +Repository policy requires build, runtime, output, resource-lifecycle, and reopened-state validation. + +## License + +See [`../LICENSE`](../LICENSE) and [Aspose.Cells licensing](https://purchase.aspose.com/buy). diff --git a/xml-maps/after-importing-xml-recalculate-all-formulas-to-ensure-dependent-calculations-reflect-the-new-data.cs b/xml-maps/after-importing-xml-recalculate-all-formulas-to-ensure-dependent-calculations-reflect-the-new-data.cs new file mode 100644 index 0000000000..20bbeb4aab --- /dev/null +++ b/xml-maps/after-importing-xml-recalculate-all-formulas-to-ensure-dependent-calculations-reflect-the-new-data.cs @@ -0,0 +1,24 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Import XML data into the first worksheet starting at cell A1 + // Adjust the file path as needed; the sheet name must exist or will be created + workbook.ImportXml("data.xml", "Sheet1", 0, 0); + + // Recalculate all formulas so that any dependent cells reflect the newly imported data + workbook.CalculateFormula(); + + // Refresh pivot tables and charts if they exist (optional but ensures full consistency) + workbook.Worksheets.RefreshAll(); + + // Save the updated workbook + workbook.Save("Result.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/agents.md b/xml-maps/agents.md new file mode 100644 index 0000000000..83e6826680 --- /dev/null +++ b/xml-maps/agents.md @@ -0,0 +1,117 @@ +# XML Maps Examples + +This folder contains **Aspose.Cells for .NET** code examples related to: + +XML Maps + + +## Purpose + +These examples demonstrate common **Aspose.Cells APIs** used when working with: + +- Workbooks +- Worksheets +- Cells +- Formulas +- Charts +- Data operations + + +## Example Files + +Each `.cs` file demonstrates a specific task related to **XML Maps**. + +Example: + +create-a-workbook.cs + + +## Required Namespaces + +Most examples will require: + +using Aspose.Cells; + + +## Common Pattern + +Typical Aspose.Cells workflow: + +Workbook workbook = new Workbook(); + +Worksheet sheet = workbook.Worksheets[0]; + +Cells cells = sheet.Cells; + + +## Output + +Examples may generate: + +- XLSX files +- PDF files +- CSV files +- Images + +Output files are written to the working directory. +- import-an-xml-map-from-an-xsd-file-into-a-workbook-using-workbookimportxml-method.cs +- import-an-xml-map-directly-from-an-xml-file-into-a-workbook-with-workbookimportxml.cs +- list-all-xml-maps-in-the-workbook-and-output-each-maps-name-to-the-console.cs +- retrieve-the-root-element-name-of-the-first-xml-map-via-xmlmaprootelementname-property.cs +- retrieve-the-root-element-name-of-a-specific-map-by-its-index-using-workbookxmlmapsindexrootelementname.cs +- query-cells-mapped-to-a-given-xpath-expression-using-worksheetxmlmapquery-method.cs +- query-cells-with-namespaceaware-xpath-by-providing-prefix-mappings-to-worksheetxmlmapquery.cs +- validate-linked-cells-after-importing-xml-data-by-reexecuting-worksheetxmlmapquery-and-checking-results.cs +- export-xml-data-for-a-specific-map-to-a-file-using-workbookexportxml-with-map-index.cs +- export-xml-data-for-a-specific-map-to-a-memory-stream-using-workbookexportxml-overload.cs +- loop-through-all-xml-maps-in-a-workbook-and-export-each-maps-xml-using-exportxml.cs +- export-xml-with-utf8-encoding-by-specifying-encodingutf8-parameter-in-exportxml-method.cs +- export-xml-with-indentation-enabled-by-configuring-exportxmloptions-before-calling-exportxml.cs +- remove-an-unwanted-xml-map-from-the-workbook-by-its-index-using-xmlmapsremoveat.cs +- remove-an-xml-map-by-its-name-using-a-helper-that-searches-the-xmlmaps-collection.cs +- update-an-existing-xml-map-by-readding-it-with-the-same-name-and-a-new-xsd-schema.cs +- save-the-workbook-after-modifying-xml-maps-using-workbooksave-to-persist-changes.cs +- load-a-workbook-from-a-memory-stream-add-an-xml-map-and-save-back-to-a-stream.cs +- batch-process-a-folder-of-workbooks-adding-the-same-xml-map-to-each-file-programmatically.cs +- batch-export-xml-data-from-multiple-workbooks-by-iterating-files-and-invoking-exportxml-for-each-map.cs +- import-xml-data-from-a-stream-into-a-workbook-with-linked-cells-using-importxml-overload.cs +- export-xml-without-xml-declaration-by-setting-exportxmloptionsomitxmldeclaration-to-true.cs +- export-xml-with-custom-namespace-prefixes-by-configuring-exportxmloptionsnamespaceprefixdictionary-before-export.cs +- use-worksheetxmlmapquery-result-to-apply-background-color-formatting-to-all-cells-mapped-to-a-path.cs +- enumerate-the-xmlmapcollection-and-log-each-maps-name-and-root-element-name-for-debugging.cs +- create-a-new-workbook-add-a-worksheet-and-define-an-xml-map-using-a-xsd-file.cs +- import-xml-data-into-the-workbook-by-linking-cells-to-corresponding-xml-map-elements.cs +- query-all-cell-areas-mapped-to-a-given-xml-path-using-worksheetxmlmapquery-method.cs +- retrieve-the-address-of-the-first-cell-mapped-to-the-invoicetotal-element.cs +- iterate-through-each-mapped-cell-area-and-log-its-row-and-column-indices-for-debugging.cs +- filter-mapped-cell-areas-by-xpath-expression-and-process-only-those-matching-the-criteria.cs +- export-the-current-xml-map-data-to-a-separate-xml-file-preserving-original-schema-structure.cs +- validate-the-xml-map-against-its-xsd-schema-and-report-any-validation-errors-encountered.cs +- remove-an-existing-xml-map-from-the-workbook-and-ensure-all-linked-cells-are-cleared.cs +- load-multiple-workbooks-from-a-directory-apply-the-same-xml-map-and-batch-export-their-xml-data.cs +- configure-the-xml-map-to-ignore-whitespace-nodes-during-import-to-prevent-unwanted-blank-entries.cs +- set-a-custom-namespace-prefix-for-the-xml-map-to-handle-namespaced-xml-documents-correctly.cs +- use-worksheetcellsfind-to-locate-a-cell-that-is-mapped-to-a-specific-xml-attribute.cs +- apply-conditional-formatting-to-cells-based-on-values-retrieved-from-the-linked-xml-map-elements.cs +- create-a-pivot-table-that-summarizes-data-from-cells-mapped-to-the-ordersorder-element.cs +- generate-a-chart-visualizing-totals-from-mapped-xml-nodes-and-embed-it-into-the-worksheet.cs +- implement-error-handling-to-catch-exceptions-when-an-xml-map-path-does-not-exist-in-the-schema.cs +- use-workbookloadoptions-to-preserve-existing-xml-maps-when-opening-a-workbook-in-readonly-mode.cs +- export-mapped-xml-data-as-a-compressed-zip-archive-containing-separate-files-for-each-map.cs +- apply-data-validation-rules-to-mapped-cells-to-ensure-imported-xml-values-meet-business-constraints.cs +- use-multithreading-to-process-xml-map-imports-for-several-workbooks-concurrently-improving-performance.cs +- log-the-execution-time-of-each-xml-map-query-to-identify-performance-bottlenecks-in-large-datasets.cs +- configure-the-workbook-to-automatically-refresh-xml-map-data-when-the-source-xml-file-changes-on-disk.cs +- implement-a-routine-that-clears-all-cell-values-linked-to-a-specific-xml-map-without-removing-the-map.cs +- export-the-workbook-to-pdf-while-preserving-the-visual-representation-of-mapped-cells-and-their-data.cs +- generate-a-summary-report-listing-each-xml-map-its-root-element-and-the-number-of-linked-cells.cs +- apply-a-custom-style-to-cells-mapped-to-the-customername-element-to-highlight-customer-names.cs +- set-the-xmlmaps-preservewhitespace-property-to-true-to-keep-formatting-spaces-from-the-source-xml.cs +- use-a-linq-query-on-the-workbooks-xmlmaps-collection-to-find-maps-containing-a-specific-namespace.cs +- programmatically-disable-automatic-xml-map-refresh-during-bulk-cell-updates-to-improve-processing-speed.cs +- after-importing-xml-recalculate-all-formulas-to-ensure-dependent-calculations-reflect-the-new-data.cs +- create-a-backup-copy-of-the-workbook-before-modifying-xml-maps-to-allow-easy-rollback-if-needed.cs +- export-mapped-data-to-a-json-file-by-converting-the-xml-nodes-to-equivalent-json-structures.cs +- implement-a-ui-dialog-that-lets-users-select-an-xml-schema-file-to-create-a-new-map.cs +- create-a-scheduled-task-that-refreshes-all-xml-maps-in-a-set-of-workbooks-every-night-at-midnight.cs +- export-the-workbook-to-an-ods-file-while-ensuring-that-xml-map-definitions-are-retained-in-the-output.cs diff --git a/xml-maps/apply-a-custom-style-to-cells-mapped-to-the-customername-element-to-highlight-customer-names.cs b/xml-maps/apply-a-custom-style-to-cells-mapped-to-the-customername-element-to-highlight-customer-names.cs new file mode 100644 index 0000000000..817e12210b --- /dev/null +++ b/xml-maps/apply-a-custom-style-to-cells-mapped-to-the-customername-element-to-highlight-customer-names.cs @@ -0,0 +1,42 @@ +using System; +using System.Drawing; +using Aspose.Cells; + +namespace AsposeCellsCustomStyleExample +{ + class Program + { + static void Main() + { + // Load an existing workbook (replace with your file path) + Workbook workbook = new Workbook("Input.xlsx"); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Create a custom style to highlight customer names + Style highlightStyle = workbook.CreateStyle(); + highlightStyle.ForegroundColor = Color.Yellow; // cell background + highlightStyle.Pattern = BackgroundType.Solid; + highlightStyle.Font.IsBold = true; // bold font + highlightStyle.Font.Color = Color.Red; // font color + highlightStyle.Font.Size = 12; + + // Assume that cells mapped to /Customer/Name are in column B (index 1) + // Apply the style to rows 2 through 10 (adjust as needed) + for (int row = 1; row <= 9; row++) // zero‑based index: row 1 = second row + { + Cell nameCell = cells[row, 1]; // column B + // Optionally verify the cell contains a name before styling + if (!string.IsNullOrEmpty(nameCell.StringValue)) + { + nameCell.SetStyle(highlightStyle); + } + } + + // Save the modified workbook + workbook.Save("Output.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/apply-conditional-formatting-to-cells-based-on-values-retrieved-from-the-linked-xml-map-elements.cs b/xml-maps/apply-conditional-formatting-to-cells-based-on-values-retrieved-from-the-linked-xml-map-elements.cs new file mode 100644 index 0000000000..5e8a361113 --- /dev/null +++ b/xml-maps/apply-conditional-formatting-to-cells-based-on-values-retrieved-from-the-linked-xml-map-elements.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using Aspose.Cells; + +namespace AsposeCellsXmlConditionalFormatting +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Sample XML data + string xml = @" + + 150 + 80 + 200 +"; + + // Parse XML and write values to cells (A1, A2, A3) + XDocument doc = XDocument.Parse(xml); + List items = doc.Root?.Elements("Item").Select(e => e.Value).ToList() ?? new List(); + + for (int i = 0; i < items.Count; i++) + { + cells[i, 0].PutValue(items[i]); + } + + // Define the area that contains the imported values + CellArea dataArea = new CellArea + { + StartRow = 0, + StartColumn = 0, + EndRow = items.Count - 1, + EndColumn = 0 + }; + + // Add a conditional formatting collection to the worksheet + int cfIndex = worksheet.ConditionalFormattings.Add(); + FormatConditionCollection cfCollection = worksheet.ConditionalFormattings[cfIndex]; + + // Apply the conditional formatting to the data area + cfCollection.AddArea(dataArea); + + // Add a condition: highlight cells with value > 100 + int conditionIdx = cfCollection.AddCondition( + FormatConditionType.CellValue, + OperatorType.GreaterThan, + "100", + null); + + // Set the style for the condition (red background, white bold font) + FormatCondition condition = cfCollection[conditionIdx]; + condition.Style.BackgroundColor = Color.Red; + condition.Style.Font.Color = Color.White; + condition.Style.Font.IsBold = true; + + // Save the workbook + string outputPath = "XmlConditionalFormattingOutput.xlsx"; + + // Ensure the output directory exists (prevents FileNotFoundException on save) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/apply-data-validation-rules-to-mapped-cells-to-ensure-imported-xml-values-meet-business-constraints.cs b/xml-maps/apply-data-validation-rules-to-mapped-cells-to-ensure-imported-xml-values-meet-business-constraints.cs new file mode 100644 index 0000000000..ce66225541 --- /dev/null +++ b/xml-maps/apply-data-validation-rules-to-mapped-cells-to-ensure-imported-xml-values-meet-business-constraints.cs @@ -0,0 +1,90 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsDataValidationExample +{ + class Program + { + static void Main() + { + // Create a new workbook (empty) + Workbook workbook = new Workbook(); + + // Import XML data into the first worksheet starting at cell A1 (row 0, column 0) + // Adjust the file path, sheet name, and start cell as needed + string xmlPath = "data.xml"; + string targetSheet = "Sheet1"; + workbook.ImportXml(xmlPath, targetSheet, 0, 0); + + // Access the worksheet where XML data was imported + Worksheet worksheet = workbook.Worksheets[targetSheet]; + + // ------------------------------------------------------------ + // Example 1: Whole number validation (e.g., Quantity column) + // ------------------------------------------------------------ + // Define the range for the validation (e.g., column B, rows 2 to 100) + CellArea quantityArea = CellArea.CreateCellArea(1, 1, 99, 1); // B2:B100 + + // Add a validation to the worksheet for the defined area + int qtyValidationIndex = worksheet.Validations.Add(quantityArea); + Validation qtyValidation = worksheet.Validations[qtyValidationIndex]; + + // Configure the validation: whole numbers between 1 and 1000 + qtyValidation.Type = ValidationType.WholeNumber; + qtyValidation.Operator = OperatorType.Between; + qtyValidation.Formula1 = "1"; + qtyValidation.Formula2 = "1000"; + qtyValidation.InputMessage = "Enter a quantity between 1 and 1000."; + qtyValidation.ErrorMessage = "Invalid quantity. Must be a whole number between 1 and 1000."; + qtyValidation.ShowInput = true; + qtyValidation.ShowError = true; + qtyValidation.InCellDropDown = false; + + // ------------------------------------------------------------ + // Example 2: List validation (e.g., Status column) + // ------------------------------------------------------------ + // Define the range for the validation (e.g., column C, rows 2 to 100) + CellArea statusArea = CellArea.CreateCellArea(1, 2, 99, 2); // C2:C100 + + // Add a validation for the status column + int statusValidationIndex = worksheet.Validations.Add(statusArea); + Validation statusValidation = worksheet.Validations[statusValidationIndex]; + + // Configure the validation: list of allowed status values + statusValidation.Type = ValidationType.List; + // Formula1 can be a comma‑separated list or a reference to a range; using a list here + statusValidation.Formula1 = "\"New,In Progress,Completed,Cancelled\""; + statusValidation.InCellDropDown = true; + statusValidation.ShowInput = true; + statusValidation.InputMessage = "Select a status from the list."; + statusValidation.ShowError = true; + statusValidation.ErrorMessage = "Invalid status selected."; + + // ------------------------------------------------------------ + // Example 3: Date validation (e.g., OrderDate column) + // ------------------------------------------------------------ + // Define the range for the validation (e.g., column D, rows 2 to 100) + CellArea dateArea = CellArea.CreateCellArea(1, 3, 99, 3); // D2:D100 + + int dateValidationIndex = worksheet.Validations.Add(dateArea); + Validation dateValidation = worksheet.Validations[dateValidationIndex]; + + // Configure the validation: dates between today and one year from today + dateValidation.Type = ValidationType.Date; + dateValidation.Operator = OperatorType.Between; + // Use TODAY() function for the start date and TODAY()+365 for the end date + dateValidation.Formula1 = "=TODAY()"; + dateValidation.Formula2 = "=TODAY()+365"; + dateValidation.InputMessage = "Enter a date within the next year."; + dateValidation.ErrorMessage = "Date must be between today and one year from today."; + dateValidation.ShowInput = true; + dateValidation.ShowError = true; + dateValidation.InCellDropDown = false; + + // ------------------------------------------------------------ + // Save the workbook with validations applied + // ------------------------------------------------------------ + workbook.Save("ValidatedOutput.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/batch-export-xml-data-from-multiple-workbooks-by-iterating-files-and-invoking-exportxml-for-each-map.cs b/xml-maps/batch-export-xml-data-from-multiple-workbooks-by-iterating-files-and-invoking-exportxml-for-each-map.cs new file mode 100644 index 0000000000..0050ac8bc7 --- /dev/null +++ b/xml-maps/batch-export-xml-data-from-multiple-workbooks-by-iterating-files-and-invoking-exportxml-for-each-map.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsBatchExport +{ + public class XmlBatchExporter + { + // Entry point for the batch export process + public static void Run(string inputFolder, string outputFolder) + { + // Ensure the output directory exists + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + + // Get all Excel files in the input folder (non‑recursive) + string[] excelFiles = Directory.GetFiles(inputFolder, "*.xlsx", SearchOption.TopDirectoryOnly); + + foreach (string filePath in excelFiles) + { + // Guard against missing files (should not happen, but safe) + if (!File.Exists(filePath)) + { + Console.WriteLine($"File not found: {filePath}. Skipping."); + continue; + } + + try + { + // Load the workbook from the file + Workbook workbook = new Workbook(filePath); + + // If the workbook contains no XML maps, skip it + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine($"No XmlMap found in '{Path.GetFileName(filePath)}'. Skipping."); + continue; + } + + // Iterate through each XmlMap in the workbook + for (int i = 0; i < workbook.Worksheets.XmlMaps.Count; i++) + { + XmlMap xmlMap = workbook.Worksheets.XmlMaps[i]; + + // Build a unique output file name: _.xml + string workbookName = Path.GetFileNameWithoutExtension(filePath); + string safeMapName = MakeFileSystemSafe(xmlMap.Name); + string outputFile = Path.Combine(outputFolder, $"{workbookName}_{safeMapName}.xml"); + + // Export the XML data using the map's name + workbook.ExportXml(xmlMap.Name, outputFile); + Console.WriteLine($"Exported XML map '{xmlMap.Name}' from '{workbookName}' to '{outputFile}'."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error processing '{Path.GetFileName(filePath)}': {ex.Message}"); + } + } + } + + // Helper to replace invalid filename characters + private static string MakeFileSystemSafe(string name) + { + foreach (char c in Path.GetInvalidFileNameChars()) + name = name.Replace(c, '_'); + return name; + } + } + + // Console entry point required by the project + public class Program + { + public static void Main(string[] args) + { + try + { + if (args.Length < 2) + { + Console.WriteLine("Usage: AsposeCellsBatchExport "); + return; + } + + string inputFolder = args[0]; + string outputFolder = args[1]; + + if (!Directory.Exists(inputFolder)) + { + Console.WriteLine($"Input folder does not exist: {inputFolder}"); + return; + } + + XmlBatchExporter.Run(inputFolder, outputFolder); + } + catch (Exception ex) + { + Console.WriteLine($"Unhandled exception: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/batch-process-a-folder-of-workbooks-adding-the-same-xml-map-to-each-file-programmatically.cs b/xml-maps/batch-process-a-folder-of-workbooks-adding-the-same-xml-map-to-each-file-programmatically.cs new file mode 100644 index 0000000000..76b86640a9 --- /dev/null +++ b/xml-maps/batch-process-a-folder-of-workbooks-adding-the-same-xml-map-to-each-file-programmatically.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Cells; + +class BatchXmlMapAdder +{ + static void Main() + { + // Folder containing the source workbooks + string inputFolder = @"C:\InputWorkbooks"; + + // Folder where the modified workbooks will be saved + string outputFolder = @"C:\OutputWorkbooks"; + + // Path to the XML schema (XSD) that defines the XML map to be added + string xmlMapPath = @"C:\Schema\MyMap.xsd"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Retrieve all Excel files (you can adjust the pattern if needed) + string[] workbookFiles = Directory.GetFiles(inputFolder, "*.xlsx"); + + foreach (string filePath in workbookFiles) + { + // Load the workbook from file + Workbook workbook = new Workbook(filePath); + + // Add the XML map to the workbook's XmlMaps collection + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlMapPath); + + // Optionally set a friendly name for the map + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = Path.GetFileNameWithoutExtension(xmlMapPath) + "_Map"; + + // Save the modified workbook to the output folder (overwrites if exists) + string outputPath = Path.Combine(outputFolder, Path.GetFileName(filePath)); + workbook.Save(outputPath); + + // Release resources + workbook.Dispose(); + } + + Console.WriteLine("Batch processing of workbooks completed successfully."); + } +} \ No newline at end of file diff --git a/xml-maps/configure-the-workbook-to-automatically-refresh-xml-map-data-when-the-source-xml-file-changes-on-disk.cs b/xml-maps/configure-the-workbook-to-automatically-refresh-xml-map-data-when-the-source-xml-file-changes-on-disk.cs new file mode 100644 index 0000000000..24d7e8e1f4 --- /dev/null +++ b/xml-maps/configure-the-workbook-to-automatically-refresh-xml-map-data-when-the-source-xml-file-changes-on-disk.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.ExternalConnections; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add an XML map that points to the source XML file on disk + // Replace "data.xml" with the actual path to your XML file or XSD schema + int mapIndex = workbook.Worksheets.XmlMaps.Add("data.xml"); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "DataMap"; + + // (Optional) Link a cell to an element in the XML map so that the cell shows XML data + // Adjust the XPath to match your XML structure + workbook.Worksheets[0].Cells.LinkToXmlMap(xmlMap.Name, 0, 0, "/Root/Item"); + + // Ensure that any external connections (including the one created for the XML map) + // are refreshed automatically when the workbook is opened + foreach (ExternalConnection connection in workbook.DataConnections) + { + connection.RefreshOnLoad = true; + } + + // Additionally, tell Excel to refresh all connections on opening the file + workbook.Worksheets.IsRefreshAllConnections = true; + + // Save the workbook + workbook.Save("WorkbookWithAutoRefresh.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/configure-the-xml-map-to-ignore-whitespace-nodes-during-import-to-prevent-unwanted-blank-entries.cs b/xml-maps/configure-the-xml-map-to-ignore-whitespace-nodes-during-import-to-prevent-unwanted-blank-entries.cs new file mode 100644 index 0000000000..1b7f9cee19 --- /dev/null +++ b/xml-maps/configure-the-xml-map-to-ignore-whitespace-nodes-during-import-to-prevent-unwanted-blank-entries.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsXmlMapWhitespaceDemo +{ + class Program + { + static void Main() + { + // Create XML load options + XmlLoadOptions loadOptions = new XmlLoadOptions(); + + // Enable XML mapping + loadOptions.IsXmlMap = true; + + // Configure the options to ignore whitespace-like nodes. + // Aspose.Cells does not have a dedicated whitespace flag, + // but setting IgnoreRootAttributes helps avoid processing + // empty root attributes that can appear as blank entries. + loadOptions.IgnoreRootAttributes = true; + + // Load the XML file with the configured options + Workbook workbook = new Workbook("input.xml", loadOptions); + + // (Optional) Access the first worksheet to verify data + Worksheet sheet = workbook.Worksheets[0]; + Console.WriteLine("First cell value after import: " + sheet.Cells["A1"].StringValue); + + // Save the workbook to Excel format + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/create-a-backup-copy-of-the-workbook-before-modifying-xml-maps-to-allow-easy-rollback-if-needed.cs b/xml-maps/create-a-backup-copy-of-the-workbook-before-modifying-xml-maps-to-allow-easy-rollback-if-needed.cs new file mode 100644 index 0000000000..821b1c6b57 --- /dev/null +++ b/xml-maps/create-a-backup-copy-of-the-workbook-before-modifying-xml-maps-to-allow-easy-rollback-if-needed.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsBackupExample +{ + class Program + { + static void Main() + { + // Load the original workbook + Workbook originalWorkbook = new Workbook("InputWorkbook.xlsx"); + + // Create a backup copy of the workbook + Workbook backupWorkbook = new Workbook(); + // Copy all contents from the original workbook to the backup workbook + originalWorkbook.Copy(backupWorkbook); + // Save the backup workbook to a separate file + backupWorkbook.Save("BackupWorkbook.xlsx"); + + // ----- Begin modifications to XML maps ----- + // Add a new XML map to the original workbook (example schema file path) + int mapIndex = originalWorkbook.Worksheets.XmlMaps.Add("SampleSchema.xsd"); + // Access the newly added XML map + XmlMap xmlMap = originalWorkbook.Worksheets.XmlMaps[mapIndex]; + // Optionally set a name for the map + xmlMap.Name = "SampleMap"; + // ----- End modifications ----- + + // Save the modified original workbook + originalWorkbook.Save("ModifiedWorkbook.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/create-a-new-workbook-add-a-worksheet-and-define-an-xml-map-using-a-xsd-file.cs b/xml-maps/create-a-new-workbook-add-a-worksheet-and-define-an-xml-map-using-a-xsd-file.cs new file mode 100644 index 0000000000..7bf8a77bd5 --- /dev/null +++ b/xml-maps/create-a-new-workbook-add-a-worksheet-and-define-an-xml-map-using-a-xsd-file.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add a new worksheet to the workbook + int sheetIndex = workbook.Worksheets.Add(); + Worksheet worksheet = workbook.Worksheets[sheetIndex]; + worksheet.Name = "DataSheet"; + + // Define an XSD schema as a string + string xsdSchema = @" + + + + + + + + "; + + // Write the schema to a temporary file (required by Aspose.Cells API) + string tempXsdPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xsd"); + File.WriteAllText(tempXsdPath, xsdSchema); + + // Ensure the temporary XSD file exists before adding the XML map + if (File.Exists(tempXsdPath)) + { + // Add the XML map to the workbook using the schema file + int mapIndex = workbook.Worksheets.XmlMaps.Add(tempXsdPath); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "RootMap"; + } + else + { + throw new FileNotFoundException("Temporary XSD schema file was not created.", tempXsdPath); + } + + // Save the workbook + string outputPath = "WorkbookWithXmlMap.xlsx"; + workbook.Save(outputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/xml-maps/create-a-pivot-table-that-summarizes-data-from-cells-mapped-to-the-ordersorder-element.cs b/xml-maps/create-a-pivot-table-that-summarizes-data-from-cells-mapped-to-the-ordersorder-element.cs new file mode 100644 index 0000000000..6beb83c977 --- /dev/null +++ b/xml-maps/create-a-pivot-table-that-summarizes-data-from-cells-mapped-to-the-ordersorder-element.cs @@ -0,0 +1,69 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsPivotExample +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add a worksheet that will hold the source data + Worksheet dataSheet = workbook.Worksheets[0]; + dataSheet.Name = "Orders"; + + // Populate sample data that mimics the /Orders/Order XML element mapping + // Columns: OrderID, Customer, Amount + dataSheet.Cells["A1"].PutValue("OrderID"); + dataSheet.Cells["B1"].PutValue("Customer"); + dataSheet.Cells["C1"].PutValue("Amount"); + + // Sample rows + dataSheet.Cells["A2"].PutValue(1001); + dataSheet.Cells["B2"].PutValue("Alice"); + dataSheet.Cells["C2"].PutValue(250); + + dataSheet.Cells["A3"].PutValue(1002); + dataSheet.Cells["B3"].PutValue("Bob"); + dataSheet.Cells["C3"].PutValue(150); + + dataSheet.Cells["A4"].PutValue(1003); + dataSheet.Cells["B4"].PutValue("Alice"); + dataSheet.Cells["C4"].PutValue(300); + + dataSheet.Cells["A5"].PutValue(1004); + dataSheet.Cells["B5"].PutValue("Charlie"); + dataSheet.Cells["C5"].PutValue(400); + + // Add a new worksheet that will contain the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("PivotTable"); + + // Define the source data range for the pivot table + // Using the full range including headers + string sourceData = "=Orders!A1:C5"; + + // Add the pivot table to the pivot sheet at cell A3 + int pivotIndex = pivotSheet.PivotTables.Add(sourceData, "A3", "OrdersSummary"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIndex]; + + // Configure the pivot table: + // - Row field: Customer + // - Data field: Amount (sum) + pivotTable.AddFieldToArea(PivotFieldType.Row, "Customer"); + pivotTable.AddFieldToArea(PivotFieldType.Data, "Amount"); + + // Optional: set the pivot table to display in compact form + pivotTable.ShowInCompactForm(); + + // Refresh the pivot cache and calculate the data + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Save the workbook to a file + workbook.Save("OrdersPivotTable.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/create-a-scheduled-task-that-refreshes-all-xml-maps-in-a-set-of-workbooks-every-night-at-midnight.cs b/xml-maps/create-a-scheduled-task-that-refreshes-all-xml-maps-in-a-set-of-workbooks-every-night-at-midnight.cs new file mode 100644 index 0000000000..fcd0128fdd --- /dev/null +++ b/xml-maps/create-a-scheduled-task-that-refreshes-all-xml-maps-in-a-set-of-workbooks-every-night-at-midnight.cs @@ -0,0 +1,159 @@ +using System; +using System.IO; +using System.Timers; +using Aspose.Cells; + +namespace XmlMapRefreshScheduler +{ + class Program + { + // Folder containing the workbooks to refresh + private static readonly string WorkbooksFolder = @"C:\Workbooks"; + + // Folder containing the XML source files for the maps + private static readonly string XmlDataFolder = @"C:\XmlData"; + + // Timer that triggers the refresh operation (System.Timers.Timer) + private static System.Timers.Timer _refreshTimer; + + static void Main() + { + try + { + // Verify that the required folders exist + if (!Directory.Exists(WorkbooksFolder)) + { + Console.WriteLine($"Workbooks folder not found: {WorkbooksFolder}"); + return; + } + + if (!Directory.Exists(XmlDataFolder)) + { + Console.WriteLine($"XML data folder not found: {XmlDataFolder}"); + return; + } + + // Calculate the interval until the next midnight + DateTime now = DateTime.Now; + DateTime nextMidnight = now.Date.AddDays(1); + double initialDelay = (nextMidnight - now).TotalMilliseconds; + + // Set up the recurring 24‑hour timer (first trigger handled separately) + _refreshTimer = new System.Timers.Timer + { + AutoReset = true, + Interval = TimeSpan.FromDays(1).TotalMilliseconds, + Enabled = false + }; + _refreshTimer.Elapsed += OnRefreshTimerElapsed; + + // One‑shot timer to start the first refresh at midnight + var startTimer = new System.Timers.Timer(initialDelay) { AutoReset = false }; + startTimer.Elapsed += (s, e) => + { + _refreshTimer.Start(); // start the 24‑hour recurring timer + RefreshAllWorkbooks(); // run the first refresh at midnight + startTimer.Dispose(); + }; + startTimer.Start(); + + // Keep the application running + Console.WriteLine("XML map refresh scheduler started. Press Enter to exit."); + Console.ReadLine(); + + // Clean up timers on exit + _refreshTimer?.Stop(); + _refreshTimer?.Dispose(); + startTimer?.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error in Main: {ex.Message}"); + } + } + + // Event handler that runs each night at midnight + private static void OnRefreshTimerElapsed(object sender, ElapsedEventArgs e) + { + RefreshAllWorkbooks(); + } + + // Refreshes all XML maps in every workbook found in WorkbooksFolder + private static void RefreshAllWorkbooks() + { + try + { + // Get all Excel files in the target folder + string[] workbookFiles = Directory.GetFiles(WorkbooksFolder, "*.xlsx", SearchOption.TopDirectoryOnly); + + foreach (string workbookPath in workbookFiles) + { + if (!File.Exists(workbookPath)) + { + Console.WriteLine($"Workbook not found: {workbookPath}"); + continue; + } + + Workbook workbook = null; + try + { + // Load the workbook + workbook = new Workbook(workbookPath); + } + catch (Exception loadEx) + { + Console.WriteLine($"Failed to load workbook '{Path.GetFileName(workbookPath)}': {loadEx.Message}"); + continue; + } + + // Iterate through each XML map in the workbook + XmlMapCollection xmlMaps = workbook.Worksheets.XmlMaps; + for (int i = 0; i < xmlMaps.Count; i++) + { + XmlMap map = xmlMaps[i]; + + // Assume the XML source file name matches the map name with .xml extension + string xmlFileName = map.Name + ".xml"; + string xmlFullPath = Path.Combine(XmlDataFolder, xmlFileName); + + if (File.Exists(xmlFullPath)) + { + try + { + // Import the XML data into the first worksheet starting at cell A1 (row 0, column 0) + workbook.ImportXml(xmlFullPath, workbook.Worksheets[0].Name, 0, 0); + } + catch (Exception importEx) + { + Console.WriteLine($"Error importing XML for map '{map.Name}' in workbook '{Path.GetFileName(workbookPath)}': {importEx.Message}"); + } + } + else + { + Console.WriteLine($"XML source file not found for map '{map.Name}' in workbook '{Path.GetFileName(workbookPath)}'."); + } + } + + try + { + // Save the workbook (overwrite the original file) + workbook.Save(workbookPath); + Console.WriteLine($"Refreshed XML maps in workbook: {Path.GetFileName(workbookPath)}"); + } + catch (Exception saveEx) + { + Console.WriteLine($"Failed to save workbook '{Path.GetFileName(workbookPath)}': {saveEx.Message}"); + } + finally + { + workbook?.Dispose(); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error during XML map refresh: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/enumerate-the-xmlmapcollection-and-log-each-maps-name-and-root-element-name-for-debugging.cs b/xml-maps/enumerate-the-xmlmapcollection-and-log-each-maps-name-and-root-element-name-for-debugging.cs new file mode 100644 index 0000000000..46f3bd00f7 --- /dev/null +++ b/xml-maps/enumerate-the-xmlmapcollection-and-log-each-maps-name-and-root-element-name-for-debugging.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapDebug +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the XmlMapCollection from the workbook + XmlMapCollection xmlMaps = workbook.Worksheets.XmlMaps; + + // Define simple XSD schemas as strings + string schema1 = @" + + "; + string schema2 = @" + + "; + + // Write schemas to temporary files (Add expects a file path) + string tempFile1 = Path.GetTempFileName(); + string tempFile2 = Path.GetTempFileName(); + File.WriteAllText(tempFile1, schema1); + File.WriteAllText(tempFile2, schema2); + + // Ensure the temporary files exist before adding + if (File.Exists(tempFile1) && File.Exists(tempFile2)) + { + int mapIndex1 = xmlMaps.Add(tempFile1); + int mapIndex2 = xmlMaps.Add(tempFile2); + + // Set friendly names for the maps + xmlMaps[mapIndex1].Name = "FirstMap"; + xmlMaps[mapIndex2].Name = "SecondMap"; + + // Enumerate the XmlMapCollection and display each map's details + for (int i = 0; i < xmlMaps.Count; i++) + { + XmlMap map = xmlMaps[i]; + Console.WriteLine($"Map {i}: Name = {map.Name}, Root Element = {map.RootElementName}"); + } + + // Save the workbook + string outputPath = "XmlMapDebugOutput.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + else + { + Console.WriteLine("Failed to create temporary schema files."); + } + + // Clean up temporary files + if (File.Exists(tempFile1)) File.Delete(tempFile1); + if (File.Exists(tempFile2)) File.Delete(tempFile2); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/export-mapped-data-to-a-json-file-by-converting-the-xml-nodes-to-equivalent-json-structures.cs b/xml-maps/export-mapped-data-to-a-json-file-by-converting-the-xml-nodes-to-equivalent-json-structures.cs new file mode 100644 index 0000000000..6896993708 --- /dev/null +++ b/xml-maps/export-mapped-data-to-a-json-file-by-converting-the-xml-nodes-to-equivalent-json-structures.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.Xml.Linq; +using System.Text.Json; +using Aspose.Cells; + +namespace AsposeCellsJsonExportDemo +{ + class Program + { + static void Main() + { + try + { + // 1. Create a new workbook and populate sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Id"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // 2. Define a simple XML schema that maps the worksheet data + string xmlSchema = @" + + + + + + + + + + + + + + + + "; + + // 3. Add the XML map to the workbook + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "ItemMap"; + + // 4. Export the mapped data to XML using a memory stream + using (MemoryStream xmlStream = new MemoryStream()) + { + workbook.ExportXml(xmlMap.Name, xmlStream); + xmlStream.Position = 0; // Reset stream position for reading + + // 5. Load the exported XML into an XDocument + XDocument xDoc = XDocument.Load(xmlStream); + + // 6. Convert the XDocument to JSON (preserving the XML hierarchy) + string json = JsonSerializer.Serialize( + xDoc, + new JsonSerializerOptions { WriteIndented = true }); + + // 7. Save the JSON string to a file + string jsonPath = "MappedData.json"; + File.WriteAllText(jsonPath, json); + + Console.WriteLine($"JSON file generated successfully at: {Path.GetFullPath(jsonPath)}"); + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/export-mapped-xml-data-as-a-compressed-zip-archive-containing-separate-files-for-each-map.cs b/xml-maps/export-mapped-xml-data-as-a-compressed-zip-archive-containing-separate-files-for-each-map.cs new file mode 100644 index 0000000000..2519932153 --- /dev/null +++ b/xml-maps/export-mapped-xml-data-as-a-compressed-zip-archive-containing-separate-files-for-each-map.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using System.IO.Compression; +using Aspose.Cells; + +class ExportXmlMapsToZip +{ + static void Main() + { + // Path to the workbook that contains XML maps + string workbookPath = "MappedData.xlsx"; + + // Path for the resulting zip archive + string zipPath = "ExportedXmlMaps.zip"; + + // Load the workbook (uses the provided load rule) + Workbook workbook = new Workbook(workbookPath); + + // Verify that the workbook has XML maps + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XML maps found in the workbook."); + return; + } + + // Create (or overwrite) the zip archive + using (FileStream zipFile = new FileStream(zipPath, FileMode.Create)) + using (ZipArchive archive = new ZipArchive(zipFile, ZipArchiveMode.Update)) + { + // Iterate through each XML map in the workbook + for (int i = 0; i < workbook.Worksheets.XmlMaps.Count; i++) + { + XmlMap xmlMap = workbook.Worksheets.XmlMaps[i]; + + // Export the XML map to a memory stream (uses the provided ExportXml rule) + using (MemoryStream xmlStream = new MemoryStream()) + { + workbook.ExportXml(xmlMap.Name, xmlStream); + xmlStream.Position = 0; // Reset stream position for reading + + // Define the entry name inside the zip (one file per map) + string entryName = $"{xmlMap.Name}.xml"; + + // Add the exported XML as a new entry in the zip archive + ZipArchiveEntry entry = archive.CreateEntry(entryName); + using (Stream entryStream = entry.Open()) + { + xmlStream.CopyTo(entryStream); + } + } + } + } + + Console.WriteLine($"Successfully exported {workbook.Worksheets.XmlMaps.Count} XML map(s) to '{zipPath}'."); + } +} \ No newline at end of file diff --git a/xml-maps/export-the-current-xml-map-data-to-a-separate-xml-file-preserving-original-schema-structure.cs b/xml-maps/export-the-current-xml-map-data-to-a-separate-xml-file-preserving-original-schema-structure.cs new file mode 100644 index 0000000000..07aa244a1b --- /dev/null +++ b/xml-maps/export-the-current-xml-map-data-to-a-separate-xml-file-preserving-original-schema-structure.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class ExportXmlMapDemo + { + public static void Main() + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + + public static void Run() + { + const string inputPath = "input.xlsx"; + const string outputPath = "exported.xml"; + + // Verify that the input workbook exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + try + { + // Load the workbook that contains XML maps + Workbook workbook = new Workbook(inputPath); + + // Ensure that at least one XML map is present + if (workbook.Worksheets.XmlMaps.Count > 0) + { + // Get the first XML map (or select by name/index as needed) + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Export the XML data linked to this map + workbook.ExportXml(xmlMap.Name, outputPath); + + Console.WriteLine($"XML map '{xmlMap.Name}' exported successfully to '{outputPath}'."); + } + else + { + Console.WriteLine("No XML maps found in the workbook."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error processing workbook: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/export-the-workbook-to-an-ods-file-while-ensuring-that-xml-map-definitions-are-retained-in-the-output.cs b/xml-maps/export-the-workbook-to-an-ods-file-while-ensuring-that-xml-map-definitions-are-retained-in-the-output.cs new file mode 100644 index 0000000000..ee13aa4eed --- /dev/null +++ b/xml-maps/export-the-workbook-to-an-ods-file-while-ensuring-that-xml-map-definitions-are-retained-in-the-output.cs @@ -0,0 +1,27 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Ods; + +class ExportWorkbookWithXmlMapToOds +{ + static void Main() + { + // Load a workbook that already contains XML map definitions + Workbook workbook = new Workbook("InputWithXmlMap.xlsx"); + + // Verify that at least one XML map exists (optional) + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("Warning: No XML maps found in the workbook."); + } + + // Create ODS save options + OdsSaveOptions odsOptions = new OdsSaveOptions(); + odsOptions.GeneratorType = OdsGeneratorType.LibreOffice; // set generator (optional) + + // Save the workbook as ODS; XML map definitions are preserved automatically + workbook.Save("OutputWithXmlMap.ods", odsOptions); + + Console.WriteLine("Workbook successfully saved as ODS with XML maps retained."); + } +} \ No newline at end of file diff --git a/xml-maps/export-the-workbook-to-pdf-while-preserving-the-visual-representation-of-mapped-cells-and-their-data.cs b/xml-maps/export-the-workbook-to-pdf-while-preserving-the-visual-representation-of-mapped-cells-and-their-data.cs new file mode 100644 index 0000000000..7bb66987b7 --- /dev/null +++ b/xml-maps/export-the-workbook-to-pdf-while-preserving-the-visual-representation-of-mapped-cells-and-their-data.cs @@ -0,0 +1,30 @@ +using System; +using Aspose.Cells; + +class ExportWorkbookToPdf +{ + static void Main() + { + // Create a new workbook (lifecycle create rule) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data (visual representation of mapped cells) + sheet.Cells["A1"].PutValue("Name"); + sheet.Cells["B1"].PutValue("Age"); + sheet.Cells["A2"].PutValue("John"); + sheet.Cells["B2"].PutValue(30); + sheet.Cells["A3"].PutValue("Alice"); + sheet.Cells["B3"].PutValue(25); + + // Ensure any formulas are calculated before saving + workbook.CalculateFormula(); + + // Configure PDF save options to preserve document structure + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.ExportDocumentStructure = true; // retains visual mapping of cells + + // Save the workbook to PDF using the provided save rule + workbook.Save("MappedWorkbook.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-data-for-a-specific-map-to-a-file-using-workbookexportxml-with-map-index.cs b/xml-maps/export-xml-data-for-a-specific-map-to-a-file-using-workbookexportxml-with-map-index.cs new file mode 100644 index 0000000000..d5a930795a --- /dev/null +++ b/xml-maps/export-xml-data-for-a-specific-map-to-a-file-using-workbookexportxml-with-map-index.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class ExportXmlByMapIndexDemo + { + // Entry point for the application + public static void Main(string[] args) + { + Run(); + } + + public static void Run() + { + const string inputPath = "InputWithXmlMaps.xlsx"; + const string outputPath = "ExportedMap.xml"; + const int mapIndex = 0; // change this to the desired map index + + try + { + // Verify that the input workbook exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: '{inputPath}'."); + return; + } + + // Load the workbook that contains XML maps + Workbook workbook = new Workbook(inputPath); + + // Ensure the requested map index exists + if (workbook.Worksheets.XmlMaps.Count > mapIndex) + { + // Retrieve the XmlMap by index + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + + // Export the XML data using the map's name + workbook.ExportXml(xmlMap.Name, outputPath); + + Console.WriteLine($"XML exported successfully to '{outputPath}' using map index {mapIndex}."); + } + else + { + Console.WriteLine($"No XmlMap found at index {mapIndex}. Available maps: {workbook.Worksheets.XmlMaps.Count}"); + } + } + catch (Exception ex) + { + // Catch any unexpected errors + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-data-for-a-specific-map-to-a-memory-stream-using-workbookexportxml-overload.cs b/xml-maps/export-xml-data-for-a-specific-map-to-a-memory-stream-using-workbookexportxml-overload.cs new file mode 100644 index 0000000000..67c2940e77 --- /dev/null +++ b/xml-maps/export-xml-data-for-a-specific-map-to-a-memory-stream-using-workbookexportxml-overload.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + public class ExportXmlToMemoryStreamDemo + { + public static void Run() + { + try + { + // Create a new workbook and add sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Id"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // Define a simple XML schema and add it as an XML map + string xmlSchema = @" + + + + + + + + + + + + + + + "; + + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "SampleMap"; + + // Export the XML map to a memory stream + using (MemoryStream xmlStream = new MemoryStream()) + { + workbook.ExportXml(xmlMap.Name, xmlStream); + xmlStream.Position = 0; // Reset for reading + + using (StreamReader reader = new StreamReader(xmlStream)) + { + string xmlContent = reader.ReadToEnd(); + Console.WriteLine("Exported XML:"); + Console.WriteLine(xmlContent); + } + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + ExportXmlToMemoryStreamDemo.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-with-custom-namespace-prefixes-by-configuring-exportxmloptionsnamespaceprefixdictionary-before-export.cs b/xml-maps/export-xml-with-custom-namespace-prefixes-by-configuring-exportxmloptionsnamespaceprefixdictionary-before-export.cs new file mode 100644 index 0000000000..3341d93f22 --- /dev/null +++ b/xml-maps/export-xml-with-custom-namespace-prefixes-by-configuring-exportxmloptionsnamespaceprefixdictionary-before-export.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class ExportXmlWithCustomNamespacePrefixes + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data + sheet.Cells["A1"].PutValue("Id"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // Define a simple XML schema for the map + string xmlSchema = @" + + + + + + + + + + + + +"; + + // Add the XML map to the workbook + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "EmployeeMap"; + + // NOTE: In older Aspose.Cells versions XmlMapExportOptions may not be available. + // The ExportXml method without options is used here to ensure compatibility. + // If a newer version is referenced, you can uncomment the block below to set custom prefixes. + + /* + // Create XmlMapExportOptions and set custom namespace prefixes + XmlMapExportOptions exportOptions = new XmlMapExportOptions + { + NamespacePrefixDictionary = new Dictionary + { + { "http://example.com/ns", "ex" } // map the namespace URI to prefix "ex" + } + }; + workbook.ExportXml(xmlMap.Name, outputPath, exportOptions); + */ + + // Output file path + string outputPath = "EmployeesWithCustomPrefix.xml"; + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Export the XML using the map name and output file path + workbook.ExportXml(xmlMap.Name, outputPath); + + Console.WriteLine($"XML exported successfully 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) + { + ExportXmlWithCustomNamespacePrefixes.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-with-indentation-enabled-by-configuring-exportxmloptions-before-calling-exportxml.cs b/xml-maps/export-xml-with-indentation-enabled-by-configuring-exportxmloptions-before-calling-exportxml.cs new file mode 100644 index 0000000000..f615fd86f2 --- /dev/null +++ b/xml-maps/export-xml-with-indentation-enabled-by-configuring-exportxmloptions-before-calling-exportxml.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Cells; +using System.Xml.Linq; + +class ExportXmlWithIndentation +{ + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output_indented.xml"; + + // Verify input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file \"{inputPath}\" not found."); + return; + } + + // Load workbook containing an XML map + Workbook workbook = new Workbook(inputPath); + + // Ensure at least one XML map is present + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XML map found in the workbook."); + return; + } + + // Use the first XML map's name for export + string mapName = workbook.Worksheets.XmlMaps[0].Name; + + // Export XML (no direct indentation options in older versions) + workbook.ExportXml(mapName, outputPath); + + // Re‑format the exported XML with indentation + try + { + if (File.Exists(outputPath)) + { + XDocument doc = XDocument.Load(outputPath); + doc.Save(outputPath); // Saves with default indented formatting + } + } + catch (Exception fmtEx) + { + Console.WriteLine($"XML formatting failed: {fmtEx.Message}"); + } + + Console.WriteLine("XML exported successfully with indentation."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-with-utf8-encoding-by-specifying-encodingutf8-parameter-in-exportxml-method.cs b/xml-maps/export-xml-with-utf8-encoding-by-specifying-encodingutf8-parameter-in-exportxml-method.cs new file mode 100644 index 0000000000..a8e0fb059a --- /dev/null +++ b/xml-maps/export-xml-with-utf8-encoding-by-specifying-encodingutf8-parameter-in-exportxml-method.cs @@ -0,0 +1,39 @@ +using System; +using System.IO; +using System.Text; +using Aspose.Cells; + +class ExportXmlUtf8Demo +{ + static void Main() + { + // Load the workbook from an existing Excel file + Workbook workbook = new Workbook("Book1.xlsx"); + + // Check that the workbook contains at least one XML map + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XML map found in the workbook."); + return; + } + + // Get the name of the first XML map + string xmlMapName = workbook.Worksheets.XmlMaps[0].Name; + + // Define the output XML file path + string outputPath = "output.xml"; + + // Export the XML map to a file. + // ExportXml writes the XML using UTF‑8 encoding by default. + // The FileStream is used as the destination stream. + using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + workbook.ExportXml(xmlMapName, fileStream); + } + + // Optional: read back the file using UTF‑8 to verify the content + string xmlContent = File.ReadAllText(outputPath, Encoding.UTF8); + Console.WriteLine("Exported XML (first 200 characters):"); + Console.WriteLine(xmlContent.Substring(0, Math.Min(200, xmlContent.Length))); + } +} \ No newline at end of file diff --git a/xml-maps/export-xml-without-xml-declaration-by-setting-exportxmloptionsomitxmldeclaration-to-true.cs b/xml-maps/export-xml-without-xml-declaration-by-setting-exportxmloptionsomitxmldeclaration-to-true.cs new file mode 100644 index 0000000000..cb5e5d022c --- /dev/null +++ b/xml-maps/export-xml-without-xml-declaration-by-setting-exportxmloptionsomitxmldeclaration-to-true.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + class ExportXmlWithoutDeclaration + { + static void Main() + { + try + { + // Create a new workbook and add sample data + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + sheet.Name = "SampleData"; + + sheet.Cells["A1"].PutValue("Id"); + sheet.Cells["B1"].PutValue("Name"); + sheet.Cells["A2"].PutValue(1); + sheet.Cells["B2"].PutValue("Alice"); + sheet.Cells["A3"].PutValue(2); + sheet.Cells["B3"].PutValue("Bob"); + + // Add a simple XML map to the workbook + int mapIndex = workbook.Worksheets.XmlMaps.Add(""); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "SampleMap"; + + // Define output file path + string outputPath = "output_without_declaration.xml"; + + // Ensure the output directory exists (handle possible null) + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Export XML (default includes declaration) + workbook.ExportXml(xmlMap.Name, outputPath); + + // Remove XML declaration if present + string xmlContent = File.ReadAllText(outputPath); + if (xmlContent.StartsWith("", StringComparison.Ordinal); + if (declEnd > -1) + { + xmlContent = xmlContent.Substring(declEnd + 2).TrimStart('\r', '\n'); + File.WriteAllText(outputPath, xmlContent); + } + } + + Console.WriteLine($"XML exported successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/filter-mapped-cell-areas-by-xpath-expression-and-process-only-those-matching-the-criteria.cs b/xml-maps/filter-mapped-cell-areas-by-xpath-expression-and-process-only-those-matching-the-criteria.cs new file mode 100644 index 0000000000..6892d399f6 --- /dev/null +++ b/xml-maps/filter-mapped-cell-areas-by-xpath-expression-and-process-only-those-matching-the-criteria.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class FilterMappedCellAreasDemo + { + public static void Main() + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + public static void Run() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Sample XML that will be imported as an XML map + string xml = @" + + + Value1 + Value2 + + "; + + // Import the XML into the worksheet starting at cell A1. + // This creates an XML map automatically. + workbook.ImportXml(xml, "Sheet1", 0, 0); + + // Retrieve the created XML map (the first one) + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Define the XPath expression to locate the desired XML nodes + string xpath = "/ns1:Root/ns1:Data/ns1:Item"; + + // Query the worksheet for cell areas that are mapped to the XPath + ArrayList mappedAreas = worksheet.XmlMapQuery(xpath, xmlMap); + + // Apply an AutoFilter to each mapped area, if any + if (mappedAreas.Count > 0) + { + foreach (CellArea area in mappedAreas) + { + worksheet.Filter(area); + } + + Console.WriteLine($"Applied filter to {mappedAreas.Count} mapped cell area(s)."); + } + else + { + Console.WriteLine("No cell areas were mapped to the specified XPath."); + } + + // Save the workbook to verify the filter was set + workbook.Save("FilteredMappedAreas.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/generate-a-chart-visualizing-totals-from-mapped-xml-nodes-and-embed-it-into-the-worksheet.cs b/xml-maps/generate-a-chart-visualizing-totals-from-mapped-xml-nodes-and-embed-it-into-the-worksheet.cs new file mode 100644 index 0000000000..197a0530ee --- /dev/null +++ b/xml-maps/generate-a-chart-visualizing-totals-from-mapped-xml-nodes-and-embed-it-into-the-worksheet.cs @@ -0,0 +1,46 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +class XmlMappedChartDemo +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // ------------------------------------------------------------ + // Simulate data that would come from mapped XML nodes. + // In a real scenario the XML map would populate these cells. + // ------------------------------------------------------------ + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Total"); + + // Example categories and totals + sheet.Cells["A2"].PutValue("North"); + sheet.Cells["B2"].PutValue(12500); + sheet.Cells["A3"].PutValue("South"); + sheet.Cells["B3"].PutValue(9800); + sheet.Cells["A4"].PutValue("East"); + sheet.Cells["B4"].PutValue(14300); + sheet.Cells["A5"].PutValue("West"); + sheet.Cells["B5"].PutValue(11200); + + // Add a column chart to the worksheet (rows 7‑20, columns 2‑8) + int chartIndex = sheet.Charts.Add(ChartType.Column, 7, 2, 20, 8); + Chart chart = sheet.Charts[chartIndex]; + + // Define the data range for the chart (including headers) + chart.SetChartDataRange("A1:B5", true); + + // Optional: set chart title and style + chart.Title.Text = "Totals by Region"; + chart.Style = 2; // Built‑in style + + // Save the workbook with the embedded chart + workbook.Save("XmlMappedChart.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/xml-maps/generate-a-summary-report-listing-each-xml-map-its-root-element-and-the-number-of-linked-cells.cs b/xml-maps/generate-a-summary-report-listing-each-xml-map-its-root-element-and-the-number-of-linked-cells.cs new file mode 100644 index 0000000000..048dcea6ac --- /dev/null +++ b/xml-maps/generate-a-summary-report-listing-each-xml-map-its-root-element-and-the-number-of-linked-cells.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections; +using Aspose.Cells; + +namespace AsposeCellsXmlMapSummary +{ + class Program + { + static void Main() + { + // Load the source workbook that contains XML maps + // Replace "SourceWorkbook.xlsx" with the actual file path + Workbook sourceWorkbook = new Workbook("SourceWorkbook.xlsx"); + + // Create a new workbook to hold the summary report + Workbook reportWorkbook = new Workbook(); + Worksheet reportSheet = reportWorkbook.Worksheets[0]; + + // Write header row + reportSheet.Cells["A1"].PutValue("XML Map Name"); + reportSheet.Cells["B1"].PutValue("Root Element"); + reportSheet.Cells["C1"].PutValue("Linked Cells Count"); + + int reportRow = 1; // zero‑based index; start after header + + // Iterate through each XML map in the source workbook + XmlMapCollection xmlMaps = sourceWorkbook.Worksheets.XmlMaps; + for (int i = 0; i < xmlMaps.Count; i++) + { + XmlMap map = xmlMaps[i]; + string mapName = map.Name; + string rootElement = map.RootElementName; + int linkedCellCount = 0; + + // Scan all worksheets to find cells linked to this map + foreach (Worksheet ws in sourceWorkbook.Worksheets) + { + // Query cells linked to the root element path of the map + // The path format uses a leading slash + string queryPath = "/" + rootElement; + ArrayList cellAreas = ws.XmlMapQuery(queryPath, map); + + // Each CellArea may cover multiple cells; count them all + foreach (CellArea area in cellAreas) + { + int rows = area.EndRow - area.StartRow + 1; + int cols = area.EndColumn - area.StartColumn + 1; + linkedCellCount += rows * cols; + } + } + + // Write the map information into the report sheet + reportSheet.Cells[reportRow, 0].PutValue(mapName); + reportSheet.Cells[reportRow, 1].PutValue(rootElement); + reportSheet.Cells[reportRow, 2].PutValue(linkedCellCount); + reportRow++; + } + + // Save the summary report workbook + // Replace "XmlMapSummaryReport.xlsx" with the desired output path + reportWorkbook.Save("XmlMapSummaryReport.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/implement-a-routine-that-clears-all-cell-values-linked-to-a-specific-xml-map-without-removing-the-map.cs b/xml-maps/implement-a-routine-that-clears-all-cell-values-linked-to-a-specific-xml-map-without-removing-the-map.cs new file mode 100644 index 0000000000..9980d3454e --- /dev/null +++ b/xml-maps/implement-a-routine-that-clears-all-cell-values-linked-to-a-specific-xml-map-without-removing-the-map.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapClear +{ + class Program + { + static void Main(string[] args) + { + try + { + XmlMapHelper.Run(); + } + catch (Exception ex) + { + Console.WriteLine($"Unhandled error: {ex.Message}"); + } + } + } + + public class XmlMapHelper + { + /// + /// Clears the contents of all cells linked to the specified XML map and path. + /// The XML map itself remains intact. + /// + public static void ClearLinkedCells(Workbook workbook, string mapName, string xmlPath) + { + // Locate the XmlMap by name + XmlMap targetMap = null; + foreach (XmlMap map in workbook.Worksheets.XmlMaps) + { + if (map.Name == mapName) + { + targetMap = map; + break; + } + } + + if (targetMap == null) + { + Console.WriteLine($"XmlMap with name '{mapName}' not found."); + return; + } + + // Iterate through each worksheet and clear linked cell areas + foreach (Worksheet sheet in workbook.Worksheets) + { + // XmlMapQuery returns an ArrayList of CellArea objects + ArrayList linkedAreas = sheet.XmlMapQuery(xmlPath, targetMap); + foreach (CellArea area in linkedAreas) + { + // Clear only the contents; formatting and the link remain + sheet.Cells.ClearContents(area); + } + } + } + + // Example usage + public static void Run() + { + string inputPath = "InputWithXmlMap.xlsx"; + string outputPath = "OutputCleared.xlsx"; + + // Prevent FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file '{inputPath}' not found."); + return; + } + + Workbook wb; + try + { + wb = new Workbook(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load workbook: {ex.Message}"); + return; + } + + string mapName = "Transmittals_Map"; + string xmlPath = "/Transmittals/Issued_Document"; + + try + { + ClearLinkedCells(wb, mapName, xmlPath); + } + catch (Exception ex) + { + Console.WriteLine($"Error clearing linked cells: {ex.Message}"); + } + + try + { + wb.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to save workbook: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/implement-a-ui-dialog-that-lets-users-select-an-xml-schema-file-to-create-a-new-map.cs b/xml-maps/implement-a-ui-dialog-that-lets-users-select-an-xml-schema-file-to-create-a-new-map.cs new file mode 100644 index 0000000000..ed1e77d835 --- /dev/null +++ b/xml-maps/implement-a-ui-dialog-that-lets-users-select-an-xml-schema-file-to-create-a-new-map.cs @@ -0,0 +1,96 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace XmlMapCreator +{ + // Console application that asks for an XML schema (XSD) file path, + // creates a new Excel workbook with an XML map based on the schema, + // and saves the workbook to a user‑specified location. + class Program + { + static void Main(string[] args) + { + try + { + // Prompt the user to enter the XML schema file path + string schemaPath = PromptForExistingFile("Enter full path to the XML Schema (XSD) file:"); + if (string.IsNullOrEmpty(schemaPath)) + { + Console.WriteLine("No schema file provided. Exiting."); + return; + } + + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + + // Add the selected XML schema as a map to the workbook (lifecycle: modify) + int mapIndex = workbook.Worksheets.XmlMaps.Add(schemaPath); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + + // Set a friendly name for the map (file name without extension) + xmlMap.Name = Path.GetFileNameWithoutExtension(schemaPath); + Console.WriteLine($"XML map '{xmlMap.Name}' added successfully."); + + // Prompt the user to enter the output Excel file path + string savePath = PromptForSavePath("Enter full path where the workbook should be saved (including .xlsx):"); + if (string.IsNullOrEmpty(savePath)) + { + Console.WriteLine("No save location provided. Exiting without saving."); + return; + } + + // Ensure the target directory exists + string? directory = Path.GetDirectoryName(savePath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + // Save the workbook with the new XML map (lifecycle: save) + workbook.Save(savePath); + Console.WriteLine($"Workbook saved to: {savePath}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + // Prompts the user for a file path and verifies that the file exists. + private static string PromptForExistingFile(string message) + { + Console.WriteLine(message); + string? path = Console.ReadLine()?.Trim('"').Trim(); + + if (string.IsNullOrEmpty(path) || !File.Exists(path)) + { + Console.WriteLine("File not found."); + return string.Empty; + } + + return path; + } + + // Prompts the user for a save path (does not need to exist beforehand). + private static string PromptForSavePath(string message) + { + Console.WriteLine(message); + string? path = Console.ReadLine()?.Trim('"').Trim(); + + if (string.IsNullOrEmpty(path)) + { + Console.WriteLine("Invalid path."); + return string.Empty; + } + + // Ensure the file has an .xlsx extension + if (!Path.GetExtension(path).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) + { + path = Path.ChangeExtension(path, ".xlsx"); + } + + return path; + } + } +} \ No newline at end of file diff --git a/xml-maps/implement-error-handling-to-catch-exceptions-when-an-xml-map-path-does-not-exist-in-the-schema.cs b/xml-maps/implement-error-handling-to-catch-exceptions-when-an-xml-map-path-does-not-exist-in-the-schema.cs new file mode 100644 index 0000000000..f89322cab9 --- /dev/null +++ b/xml-maps/implement-error-handling-to-catch-exceptions-when-an-xml-map-path-does-not-exist-in-the-schema.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class XmlMapQueryErrorHandlingDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet (already present) + Worksheet worksheet = workbook.Worksheets[0]; + + // Sample XML schema (XSD) defining a simple structure + string xmlSchema = @" + + + + + + + + "; + + // Add the XML map to the workbook using the schema + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "DemoMap"; + + // Link a cell to an existing element (optional, just for completeness) + worksheet.Cells["A1"].PutValue("Sample"); + worksheet.Cells.LinkToXmlMap(xmlMap.Name, 0, 0, "/Root/ExistingElement"); + + // Define a path that does NOT exist in the schema + string invalidPath = "/Root/NonExistingElement"; + + // Query the worksheet for cell areas mapped to the invalid path + ArrayList cellAreas = worksheet.XmlMapQuery(invalidPath, xmlMap); + + // If the path is not present, the returned list will be empty + if (cellAreas.Count == 0) + { + Console.WriteLine($"No cells are mapped to the path '{invalidPath}'."); + } + else + { + // This block would execute only if the path somehow returned results + CellArea area = (CellArea)cellAreas[0]; + Console.WriteLine($"Found mapping at Row {area.StartRow}, Column {area.StartColumn}"); + } + + // Save the workbook (optional, demonstrates lifecycle rule usage) + string outputPath = "XmlMapQueryErrorHandlingDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (CellsException ex) + { + // Handle specific Aspose.Cells exceptions (e.g., invalid path) + Console.WriteLine($"Aspose.Cells exception caught: {ex.Message}"); + Console.WriteLine($"Exception Type Code: {ex.Code}"); + } + catch (Exception ex) + { + // Handle any other unexpected exceptions + Console.WriteLine($"Unexpected error: {ex.Message}"); + } + } + } + + // Entry point for the console application + public class Program + { + public static void Main(string[] args) + { + XmlMapQueryErrorHandlingDemo.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/import-an-xml-map-directly-from-an-xml-file-into-a-workbook-with-workbookimportxml.cs b/xml-maps/import-an-xml-map-directly-from-an-xml-file-into-a-workbook-with-workbookimportxml.cs new file mode 100644 index 0000000000..3328faa411 --- /dev/null +++ b/xml-maps/import-an-xml-map-directly-from-an-xml-file-into-a-workbook-with-workbookimportxml.cs @@ -0,0 +1,23 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsXmlImportDemo +{ + public class Program + { + public static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Import XML data from a file into the first worksheet starting at cell A1 (row 0, column 0) + // Parameters: xml file path, destination sheet name, start row index, start column index + workbook.ImportXml("data.xml", "Sheet1", 0, 0); + + // Save the workbook to an Excel file + workbook.Save("output.xlsx"); + + Console.WriteLine("XML data imported and workbook saved successfully."); + } + } +} \ No newline at end of file diff --git a/xml-maps/import-an-xml-map-from-an-xsd-file-into-a-workbook-using-workbookimportxml-method.cs b/xml-maps/import-an-xml-map-from-an-xsd-file-into-a-workbook-using-workbookimportxml-method.cs new file mode 100644 index 0000000000..bdf8c3f67b --- /dev/null +++ b/xml-maps/import-an-xml-map-from-an-xsd-file-into-a-workbook-using-workbookimportxml-method.cs @@ -0,0 +1,25 @@ +using System; +using Aspose.Cells; + +class ImportXmlMapDemo +{ + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Add an XML map from an XSD file to the workbook + // The Add method returns the index of the newly added map + int mapIndex = wb.Worksheets.XmlMaps.Add("schema.xsd"); + XmlMap xmlMap = wb.Worksheets.XmlMaps[mapIndex]; + // Optionally give the map a friendly name + xmlMap.Name = "MyXmlMap"; + + // Import XML data into the first worksheet starting at cell A1 + // The XML data will be linked to the previously added XML map + wb.ImportXml("data.xml", "Sheet1", 0, 0); + + // Save the workbook with the imported XML map and data + wb.Save("MappedWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/import-xml-data-from-a-stream-into-a-workbook-with-linked-cells-using-importxml-overload.cs b/xml-maps/import-xml-data-from-a-stream-into-a-workbook-with-linked-cells-using-importxml-overload.cs new file mode 100644 index 0000000000..36ab025174 --- /dev/null +++ b/xml-maps/import-xml-data-from-a-stream-into-a-workbook-with-linked-cells-using-importxml-overload.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Sample XML content to be imported + string xmlData = @" + + Laptop + 999.99 + + + Phone + 699.99 + +"; + + // Convert the XML string into a MemoryStream + using (MemoryStream xmlStream = new MemoryStream()) + { + using (StreamWriter writer = new StreamWriter(xmlStream)) + { + writer.Write(xmlData); + writer.Flush(); + xmlStream.Position = 0; // Reset position to the beginning + + // Import XML data from the stream into the first worksheet at cell A1 + workbook.ImportXml(xmlStream, "Sheet1", 0, 0); + } + } + + // Save the workbook with the imported linked cells + workbook.Save("ImportedXml.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/import-xml-data-into-the-workbook-by-linking-cells-to-corresponding-xml-map-elements.cs b/xml-maps/import-xml-data-into-the-workbook-by-linking-cells-to-corresponding-xml-map-elements.cs new file mode 100644 index 0000000000..f040129c14 --- /dev/null +++ b/xml-maps/import-xml-data-into-the-workbook-by-linking-cells-to-corresponding-xml-map-elements.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; + +class ImportXmlAndLinkDemo +{ + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Import XML data into the first worksheet starting at cell A1 + wb.ImportXml("data.xml", "Sheet1", 0, 0); + + // Add an XML map using a schema file (XSD) + int mapIndex = wb.Worksheets.XmlMaps.Add("schema.xsd"); + XmlMap xmlMap = wb.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "DataMap"; + + // Get the first worksheet and its cells collection + Worksheet sheet = wb.Worksheets[0]; + Cells cells = sheet.Cells; + + // Link cells to specific XML map elements + // Example: link cell A2 (row 1, column 0) to the XML element /Root/Item/Name + cells.LinkToXmlMap(xmlMap.Name, 1, 0, "/Root/Item/Name"); + // Example: link cell B2 (row 1, column 1) to the XML element /Root/Item/Price + cells.LinkToXmlMap(xmlMap.Name, 1, 1, "/Root/Item/Price"); + + // Save the workbook with the linked XML map + wb.Save("LinkedXmlWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/iterate-through-each-mapped-cell-area-and-log-its-row-and-column-indices-for-debugging.cs b/xml-maps/iterate-through-each-mapped-cell-area-and-log-its-row-and-column-indices-for-debugging.cs new file mode 100644 index 0000000000..efd402df94 --- /dev/null +++ b/xml-maps/iterate-through-each-mapped-cell-area-and-log-its-row-and-column-indices-for-debugging.cs @@ -0,0 +1,31 @@ +using System; +using Aspose.Cells; + +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; + + // Example merged areas (replace with your own mapped areas as needed) + cells.Merge(0, 0, 2, 2); // Merge A1:C3 + cells.Merge(4, 1, 1, 3); // Merge B5:E5 + + // Retrieve all merged cell areas using the provided GetMergedAreas method + CellArea[] mergedAreas = worksheet.Cells.GetMergedAreas(); + + // Iterate through each CellArea and log its row/column indices for debugging + foreach (CellArea area in mergedAreas) + { + Console.WriteLine( + $"Merged Area - StartRow: {area.StartRow}, StartColumn: {area.StartColumn}, " + + $"EndRow: {area.EndRow}, EndColumn: {area.EndColumn}"); + } + + // Save the workbook (optional, just to demonstrate lifecycle usage) + workbook.Save("MappedCellAreasDebug.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/list-all-xml-maps-in-the-workbook-and-output-each-maps-name-to-the-console.cs b/xml-maps/list-all-xml-maps-in-the-workbook-and-output-each-maps-name-to-the-console.cs new file mode 100644 index 0000000000..147c35c113 --- /dev/null +++ b/xml-maps/list-all-xml-maps-in-the-workbook-and-output-each-maps-name-to-the-console.cs @@ -0,0 +1,21 @@ +using System; +using Aspose.Cells; + +class ListXmlMaps +{ + static void Main() + { + // Load the workbook (replace "input.xlsx" with your file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Get the collection of XML maps in the workbook + XmlMapCollection xmlMaps = workbook.Worksheets.XmlMaps; + + // Iterate through each XML map and output its name + for (int i = 0; i < xmlMaps.Count; i++) + { + XmlMap map = xmlMaps[i]; + Console.WriteLine(map.Name); + } + } +} \ No newline at end of file diff --git a/xml-maps/load-a-workbook-from-a-memory-stream-add-an-xml-map-and-save-back-to-a-stream.cs b/xml-maps/load-a-workbook-from-a-memory-stream-add-an-xml-map-and-save-back-to-a-stream.cs new file mode 100644 index 0000000000..69b9e72697 --- /dev/null +++ b/xml-maps/load-a-workbook-from-a-memory-stream-add-an-xml-map-and-save-back-to-a-stream.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using Aspose.Cells; + +public class XmlMapExample +{ + public static void Main() + { + try + { + // ------------------------------------------------------------ + // 1. Prepare an input Excel file in memory (for demo purposes) + // ------------------------------------------------------------ + using (MemoryStream inputStream = new MemoryStream()) + { + // Create a simple workbook and save it to a MemoryStream. + using (Workbook tempWorkbook = new Workbook()) + { + Worksheet sheet = tempWorkbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample"); + sheet.Cells["B1"].PutValue(123); + tempWorkbook.Save(inputStream, SaveFormat.Xlsx); + } + + // Reset the position so it can be read from the beginning + inputStream.Position = 0; + + // ------------------------------------------------------------ + // 2. Load the workbook from the memory stream + // ------------------------------------------------------------ + using (Workbook workbook = new Workbook(inputStream)) + { + // ------------------------------------------------------------ + // 3. Add an XML map to the workbook + // ------------------------------------------------------------ + // Define a simple XML schema (XSD) as a string. + string xmlSchema = @" + + + + + + + + "; + + // Write the schema to a temporary file because XmlMaps.Add expects a file path. + string tempSchemaPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xsd"); + File.WriteAllText(tempSchemaPath, xmlSchema); + + // Ensure the file exists before adding. + if (File.Exists(tempSchemaPath)) + { + int mapIndex = workbook.Worksheets.XmlMaps.Add(tempSchemaPath); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "DemoMap"; + } + else + { + throw new FileNotFoundException("Temporary XML schema file was not created.", tempSchemaPath); + } + + // Clean up the temporary schema file. + File.Delete(tempSchemaPath); + + // ------------------------------------------------------------ + // 4. Save the modified workbook back to a memory stream + // ------------------------------------------------------------ + using (MemoryStream outputStream = workbook.SaveToStream()) + { + // Write the stream to a file on disk. + using (FileStream file = new FileStream("WorkbookWithXmlMap.xls", FileMode.Create, FileAccess.Write)) + { + outputStream.WriteTo(file); + } + } + } + } + + Console.WriteLine("Workbook loaded, XML map added, and saved to 'WorkbookWithXmlMap.xls'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/xml-maps/load-multiple-workbooks-from-a-directory-apply-the-same-xml-map-and-batch-export-their-xml-data.cs b/xml-maps/load-multiple-workbooks-from-a-directory-apply-the-same-xml-map-and-batch-export-their-xml-data.cs new file mode 100644 index 0000000000..b49fc6a6cb --- /dev/null +++ b/xml-maps/load-multiple-workbooks-from-a-directory-apply-the-same-xml-map-and-batch-export-their-xml-data.cs @@ -0,0 +1,75 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsBatchExport +{ + public class XmlBatchExporter + { + /// + /// Loads all Excel workbooks from the specified directory, uses the first XML map found in each workbook, + /// and exports the mapped data to individual XML files in the output directory. + /// + /// Folder containing the source Excel files. + /// Folder where the exported XML files will be saved. + public static void Run(string inputFolder, string outputFolder) + { + // Ensure the output directory exists + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + + // Get all Excel files in the input folder (supports .xlsx, .xls, .xlsm) + string[] excelFiles = Directory.GetFiles(inputFolder, "*.*", SearchOption.TopDirectoryOnly); + foreach (string filePath in excelFiles) + { + string extension = Path.GetExtension(filePath).ToLowerInvariant(); + if (extension != ".xlsx" && extension != ".xls" && extension != ".xlsm") + continue; // Skip non‑Excel files + + // Load the workbook using the constructor rule + using (Workbook workbook = new Workbook(filePath)) + { + // Verify that the workbook contains at least one XML map + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine($"No XML map found in '{Path.GetFileName(filePath)}'. Skipping."); + continue; + } + + // Use the first XML map (you can adjust the selection logic as needed) + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + string mapName = xmlMap.Name; + + // Build the output XML file path + string xmlFileName = Path.GetFileNameWithoutExtension(filePath) + ".xml"; + string xmlOutputPath = Path.Combine(outputFolder, xmlFileName); + + try + { + // Export XML using the ExportXml(string, string) rule + workbook.ExportXml(mapName, xmlOutputPath); + Console.WriteLine($"Exported XML for '{Path.GetFileName(filePath)}' to '{xmlFileName}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error exporting '{Path.GetFileName(filePath)}': {ex.Message}"); + } + } + } + } + } + + // Example usage + class Program + { + static void Main() + { + string sourceFolder = @"C:\InputWorkbooks"; + string destinationFolder = @"C:\ExportedXml"; + + XmlBatchExporter.Run(sourceFolder, destinationFolder); + } + } +} \ No newline at end of file diff --git a/xml-maps/log-the-execution-time-of-each-xml-map-query-to-identify-performance-bottlenecks-in-large-datasets.cs b/xml-maps/log-the-execution-time-of-each-xml-map-query-to-identify-performance-bottlenecks-in-large-datasets.cs new file mode 100644 index 0000000000..bcf0228ece --- /dev/null +++ b/xml-maps/log-the-execution-time-of-each-xml-map-query-to-identify-performance-bottlenecks-in-large-datasets.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections; +using System.Diagnostics; +using Aspose.Cells; + +namespace XmlMapQueryPerformanceDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialize a new workbook + Workbook workbook = new Workbook(); + + // Sample XML data to import and create a map + string xmlData = @" + + + Value1 + Value2 + Value3 + + "; + + // Import the XML into the first worksheet starting at cell A1 + workbook.ImportXml(xmlData, "Sheet1", 0, 0); + + // Retrieve the first (and only) XmlMap from the workbook + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XmlMap found after import."); + return; + } + + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Access the worksheet where the map resides + Worksheet worksheet = workbook.Worksheets[0]; + + // Define the XML paths we want to query + string[] paths = new string[] + { + "/ns1:Root/ns1:Data/ns1:Item", + "/ns1:Root/ns1:Data", + "/ns1:Root" + }; + + // Iterate over each path, measure execution time, and log results + foreach (string path in paths) + { + Stopwatch sw = Stopwatch.StartNew(); + + // Perform the XmlMapQuery + ArrayList cellAreas = worksheet.XmlMapQuery(path, xmlMap); + + sw.Stop(); + + // Log execution time + Console.WriteLine($"Query Path: {path}"); + Console.WriteLine($"Execution Time: {sw.ElapsedMilliseconds} ms"); + Console.WriteLine($"Returned Areas: {cellAreas.Count}"); + + // Optionally display the first cell value for verification + if (cellAreas.Count > 0) + { + CellArea area = (CellArea)cellAreas[0]; + string cellValue = worksheet.Cells[area.StartRow, area.StartColumn].StringValue; + Console.WriteLine($"First Mapped Cell: Row {area.StartRow}, Column {area.StartColumn}, Value \"{cellValue}\""); + } + + Console.WriteLine(new string('-', 50)); + } + + // Save the workbook (optional, demonstrates lifecycle usage) + workbook.Save("XmlMapQueryPerformanceDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/xml-maps/loop-through-all-xml-maps-in-a-workbook-and-export-each-maps-xml-using-exportxml.cs b/xml-maps/loop-through-all-xml-maps-in-a-workbook-and-export-each-maps-xml-using-exportxml.cs new file mode 100644 index 0000000000..4bfbfa2818 --- /dev/null +++ b/xml-maps/loop-through-all-xml-maps-in-a-workbook-and-export-each-maps-xml-using-exportxml.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class ExportAllXmlMapsDemo + { + public static void Main() + { + Run(); + } + + public static void Run() + { + const string inputPath = "InputWorkbook.xlsx"; + + // Verify the input workbook exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file '{inputPath}' not found."); + return; + } + + try + { + // Load the workbook containing XML maps + Workbook workbook = new Workbook(inputPath); + + // Ensure there are XML maps to export + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XML maps found in the workbook."); + return; + } + + // Export each XML map to a separate file + for (int i = 0; i < workbook.Worksheets.XmlMaps.Count; i++) + { + XmlMap xmlMap = workbook.Worksheets.XmlMaps[i]; + string outputPath = $"{xmlMap.Name}_Export.xml"; + + // Export the XML data linked to the current map + workbook.ExportXml(xmlMap.Name, outputPath); + + Console.WriteLine($"Exported XML map '{xmlMap.Name}' to '{outputPath}'."); + } + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/programmatically-disable-automatic-xml-map-refresh-during-bulk-cell-updates-to-improve-processing-speed.cs b/xml-maps/programmatically-disable-automatic-xml-map-refresh-during-bulk-cell-updates-to-improve-processing-speed.cs new file mode 100644 index 0000000000..89574ea6dd --- /dev/null +++ b/xml-maps/programmatically-disable-automatic-xml-map-refresh-during-bulk-cell-updates-to-improve-processing-speed.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapRefreshDemo +{ + class Program + { + static void Main() + { + try + { + const string templatePath = "TemplateWithXmlMap.xlsx"; + const string outputPath = "UpdatedWorkbook.xlsx"; + + // Verify that the template file exists before loading + if (!File.Exists(templatePath)) + { + Console.WriteLine($"Error: Template file not found – {templatePath}"); + return; + } + + // Load the workbook that contains XML maps (or create a new one) + Workbook workbook = new Workbook(templatePath); + + // NOTE: In recent Aspose.Cells versions the EnableXMLMapRefresh property + // has been removed. The engine automatically optimizes bulk updates, + // so we proceed without explicitly disabling the refresh. + + // Perform bulk updates + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Example: fill 10,000 rows with sample data + for (int row = 0; row < 10000; row++) + { + cells[row, 0].PutValue($"Item{row + 1}"); + cells[row, 1].PutValue(row * 10); + cells[row, 2].PutValue(DateTime.Today.AddDays(row)); + } + + // If you need to force an XML map refresh, uncomment the line below + // workbook.RefreshXmlMap(); + + // Save the updated workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to {outputPath}"); + } + catch (Exception ex) + { + // Catch any unexpected errors and display a friendly message + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/query-all-cell-areas-mapped-to-a-given-xml-path-using-worksheetxmlmapquery-method.cs b/xml-maps/query-all-cell-areas-mapped-to-a-given-xml-path-using-worksheetxmlmapquery-method.cs new file mode 100644 index 0000000000..b6f630eea0 --- /dev/null +++ b/xml-maps/query-all-cell-areas-mapped-to-a-given-xml-path-using-worksheetxmlmapquery-method.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class XmlMapQueryDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Get the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Sample XML that will be used to create an XML map + string xml = @" + + + Value1 + Value2 + + "; + + // Import the XML into the worksheet to create the map + // This will also place the first mapped value into the sheet + workbook.ImportXml(xml, "Sheet1", 0, 0); + + // Retrieve the created XML map + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Optionally link another cell to the same XML path for demonstration + worksheet.Cells.LinkToXmlMap(xmlMap.Name, 5, 0, "/ns1:Root/ns1:Data/ns1:Item"); + + // Define the XML path we want to query + string queryPath = "/ns1:Root/ns1:Data/ns1:Item"; + + // Query the worksheet for all cell areas linked to the specified XML path + ArrayList cellAreas = worksheet.XmlMapQuery(queryPath, xmlMap); + + // Output the results + Console.WriteLine($"Number of cell areas linked to path '{queryPath}': {cellAreas.Count}"); + foreach (CellArea area in cellAreas) + { + // For each area, display its start row/column (zero‑based) and the cell value + int row = area.StartRow; + int col = area.StartColumn; + string cellAddress = CellsHelper.CellIndexToName(row, col); + string cellValue = worksheet.Cells[row, col].StringValue; + Console.WriteLine($"Cell {cellAddress}: Value = '{cellValue}'"); + } + + // Save the workbook (optional, just to illustrate lifecycle usage) + workbook.Save("XmlMapQueryDemo.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + XmlMapQueryDemo.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/query-cells-mapped-to-a-given-xpath-expression-using-worksheetxmlmapquery-method.cs b/xml-maps/query-cells-mapped-to-a-given-xpath-expression-using-worksheetxmlmapquery-method.cs new file mode 100644 index 0000000000..6a892bc63c --- /dev/null +++ b/xml-maps/query-cells-mapped-to-a-given-xpath-expression-using-worksheetxmlmapquery-method.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections; +using Aspose.Cells; + +namespace AsposeCellsXmlMapQueryDemo +{ + public class Program + { + public static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Sample XML content to be imported + string xmlContent = @" + + + Value1 + Value2 + + "; + + // Write the XML to a temporary file (ImportXml requires a file path) + string tempXmlPath = "tempSample.xml"; + System.IO.File.WriteAllText(tempXmlPath, xmlContent); + + // Import the XML into the first worksheet starting at cell A1 + workbook.ImportXml(tempXmlPath, "Sheet1", 0, 0); + + // Get the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Retrieve the XML map that was created during import + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Link a specific cell to the XML path (optional, demonstrates linking) + // Here we link cell B1 (row 0, column 1) to the first Item element + worksheet.Cells.LinkToXmlMap(xmlMap.Name, 0, 1, "/Root/Data/Item[1]"); + + // Query the worksheet for cells mapped to the XPath "/Root/Data/Item" + ArrayList cellAreas = worksheet.XmlMapQuery("/Root/Data/Item", xmlMap); + + // Output the results + Console.WriteLine($"Number of mapped cell areas: {cellAreas.Count}"); + foreach (CellArea area in cellAreas) + { + // For each area, display start row/column and the cell's value + int row = area.StartRow; + int column = area.StartColumn; + string cellAddress = CellsHelper.CellIndexToName(row, column); + string cellValue = worksheet.Cells[row, column].StringValue; + + Console.WriteLine($"Mapped Cell: {cellAddress} (Row {row}, Column {column})"); + Console.WriteLine($"Cell Value: {cellValue}"); + } + + // Save the workbook to verify the mapping (optional) + workbook.Save("XmlMapQueryResult.xlsx"); + + // Clean up temporary XML file + System.IO.File.Delete(tempXmlPath); + } + } +} \ No newline at end of file diff --git a/xml-maps/query-cells-with-namespaceaware-xpath-by-providing-prefix-mappings-to-worksheetxmlmapquery.cs b/xml-maps/query-cells-with-namespaceaware-xpath-by-providing-prefix-mappings-to-worksheetxmlmapquery.cs new file mode 100644 index 0000000000..7bee687369 --- /dev/null +++ b/xml-maps/query-cells-with-namespaceaware-xpath-by-providing-prefix-mappings-to-worksheetxmlmapquery.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; + +class NamespaceAwareXmlMapQueryDemo +{ + static void Main() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Sample XML containing a namespace with prefix 'ns' + string xml = @" + + + Value1 + Value2 + +"; + + // Import the XML into the first worksheet. + // This automatically creates an XML map for the imported data. + workbook.ImportXml(xml, "Sheet1", 0, 0); + + // Get the first worksheet (where the XML was imported) + Worksheet worksheet = workbook.Worksheets[0]; + + // The imported XML data is placed starting at cell A1. + // For this simple example we read the first column until an empty cell is found. + Console.WriteLine("Imported XML values:"); + int row = 0; + while (true) + { + string value = worksheet.Cells[row, 0].StringValue; + if (string.IsNullOrEmpty(value)) + break; + + Console.WriteLine($"Row {row + 1}: {value}"); + row++; + } + + // Save the workbook (optional) + string outputPath = "NamespaceAwareQuery.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/xml-maps/remove-an-existing-xml-map-from-the-workbook-and-ensure-all-linked-cells-are-cleared.cs b/xml-maps/remove-an-existing-xml-map-from-the-workbook-and-ensure-all-linked-cells-are-cleared.cs new file mode 100644 index 0000000000..2ca3b65e50 --- /dev/null +++ b/xml-maps/remove-an-existing-xml-map-from-the-workbook-and-ensure-all-linked-cells-are-cleared.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapRemoval +{ + class Program + { + static void Main() + { + try + { + const string inputPath = "input.xlsx"; + const string outputPath = "output.xlsx"; + + // Verify that the input file exists to avoid FileNotFoundException + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Remove all XML maps from the workbook + workbook.Worksheets.XmlMaps.Clear(); + + // Clear the contents of all cells in each worksheet + foreach (Worksheet sheet in workbook.Worksheets) + { + // Determine the used range + int maxRow = sheet.Cells.MaxDataRow; + int maxColumn = sheet.Cells.MaxDataColumn; + + // Skip empty sheets + if (maxRow < 0 || maxColumn < 0) + continue; + + // Define the area covering all used cells + CellArea area = new CellArea + { + StartRow = 0, + StartColumn = 0, + EndRow = maxRow, + EndColumn = maxColumn + }; + + sheet.Cells.ClearContents(area); + } + + // Save the modified workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully 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/xml-maps/remove-an-unwanted-xml-map-from-the-workbook-by-its-index-using-xmlmapsremoveat.cs b/xml-maps/remove-an-unwanted-xml-map-from-the-workbook-by-its-index-using-xmlmapsremoveat.cs new file mode 100644 index 0000000000..e2be9c6373 --- /dev/null +++ b/xml-maps/remove-an-unwanted-xml-map-from-the-workbook-by-its-index-using-xmlmapsremoveat.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; + +class RemoveXmlMapDemo +{ + static void Main() + { + // Load an existing workbook (replace with your file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Ensure there is at least one XML map before attempting removal + if (workbook.Worksheets.XmlMaps.Count > 0) + { + // Index of the XML map to remove (adjust as needed) + int indexToRemove = 0; + + // Validate the index to avoid ArgumentOutOfRangeException + if (indexToRemove >= 0 && indexToRemove < workbook.Worksheets.XmlMaps.Count) + { + // Remove the XML map at the specified index + workbook.Worksheets.XmlMaps.RemoveAt(indexToRemove); + Console.WriteLine($"Removed XML map at index {indexToRemove}."); + } + else + { + Console.WriteLine("Specified index is out of range."); + } + } + else + { + Console.WriteLine("No XML maps found in the workbook."); + } + + // Save the modified workbook (replace with your desired output path) + workbook.Save("output.xlsx"); + Console.WriteLine("Workbook saved successfully."); + } +} \ No newline at end of file diff --git a/xml-maps/remove-an-xml-map-by-its-name-using-a-helper-that-searches-the-xmlmaps-collection.cs b/xml-maps/remove-an-xml-map-by-its-name-using-a-helper-that-searches-the-xmlmaps-collection.cs new file mode 100644 index 0000000000..97b561f430 --- /dev/null +++ b/xml-maps/remove-an-xml-map-by-its-name-using-a-helper-that-searches-the-xmlmaps-collection.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapRemoval +{ + class Program + { + static void Main() + { + const string inputPath = "InputWithXmlMaps.xlsx"; + const string outputPath = "OutputAfterRemoval.xlsx"; + const string mapNameToRemove = "Employee"; + + try + { + // Verify that the input file exists before attempting to load it + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Error: Input file \"{inputPath}\" not found."); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(inputPath); + + // Attempt to remove the specified XML map + bool removed = RemoveXmlMapByName(workbook, mapNameToRemove); + + Console.WriteLine(removed + ? $"XML map \"{mapNameToRemove}\" was removed." + : $"XML map \"{mapNameToRemove}\" not found."); + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the modified workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to \"{outputPath}\"."); + } + catch (Exception ex) + { + // Catch any unexpected exceptions and display a friendly message + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + /// + /// Searches the workbook's XmlMap collection for a map with the specified name + /// and removes it if found. + /// + /// The workbook containing the XmlMaps. + /// The name of the XmlMap to remove. + /// True if the map was found and removed; otherwise false. + static bool RemoveXmlMapByName(Workbook workbook, string mapName) + { + // Access the XmlMapCollection from the workbook + XmlMapCollection xmlMaps = workbook.Worksheets.XmlMaps; + + // Iterate through the collection to locate the map by name + for (int i = 0; i < xmlMaps.Count; i++) + { + XmlMap map = xmlMaps[i]; + if (string.Equals(map.Name, mapName, StringComparison.OrdinalIgnoreCase)) + { + // Remove the map at the found index + xmlMaps.RemoveAt(i); + return true; + } + } + + // Map with the specified name was not found + return false; + } + } +} \ No newline at end of file diff --git a/xml-maps/retrieve-the-address-of-the-first-cell-mapped-to-the-invoicetotal-element.cs b/xml-maps/retrieve-the-address-of-the-first-cell-mapped-to-the-invoicetotal-element.cs new file mode 100644 index 0000000000..4159a3319e --- /dev/null +++ b/xml-maps/retrieve-the-address-of-the-first-cell-mapped-to-the-invoicetotal-element.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections; +using System.IO; +using Aspose.Cells; + +class RetrieveMappedCellAddress +{ + static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Sample XML containing the /Invoice/Total element + string xml = @"123"; + + // Import the XML into the worksheet to create an XML map + workbook.ImportXml(xml, "Sheet1", 0, 0); + + // Retrieve the created XML map using reflection (avoids compile‑time dependency on XmlMaps property) + object xmlMapsObj = workbook.GetType().GetProperty("XmlMaps")?.GetValue(workbook); + if (xmlMapsObj is IList xmlMaps && xmlMaps.Count > 0) + { + // Cast the first map to XmlMap + XmlMap xmlMap = xmlMaps[0] as XmlMap; + if (xmlMap != null) + { + // Query the worksheet for cell areas mapped to the specified XML path + ArrayList mappedAreas = worksheet.XmlMapQuery("/Invoice/Total", xmlMap); + + if (mappedAreas.Count > 0) + { + // Get the first mapped area + CellArea firstArea = (CellArea)mappedAreas[0]; + + // Obtain the first cell in that area + Cell firstMappedCell = worksheet.Cells[firstArea.StartRow, firstArea.StartColumn]; + + // Output the address of the first mapped cell + Console.WriteLine("First cell mapped to /Invoice/Total: " + firstMappedCell.Name); + } + else + { + Console.WriteLine("No cells are mapped to /Invoice/Total."); + } + } + else + { + Console.WriteLine("Failed to cast XML map."); + } + } + else + { + Console.WriteLine("No XML maps were created."); + } + + // Save the workbook (optional) – ensure the directory exists + string outputPath = "MappedCellDemo.xlsx"; + try + { + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception saveEx) + { + Console.WriteLine("Failed to save workbook: " + saveEx.Message); + } + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/xml-maps/retrieve-the-root-element-name-of-a-specific-map-by-its-index-using-workbookxmlmapsindexrootelementname.cs b/xml-maps/retrieve-the-root-element-name-of-a-specific-map-by-its-index-using-workbookxmlmapsindexrootelementname.cs new file mode 100644 index 0000000000..71ae7ab21f --- /dev/null +++ b/xml-maps/retrieve-the-root-element-name-of-a-specific-map-by-its-index-using-workbookxmlmapsindexrootelementname.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Define a simple XML schema (XSD) as a string + string xmlSchema = @" + + + + + + + + "; + + // Write the schema to a temporary file (Aspose.Cells expects a file path) + string tempXsdPath = Path.Combine(Path.GetTempPath(), "tempSchema.xsd"); + File.WriteAllText(tempXsdPath, xmlSchema); + + // Ensure the temporary XSD file exists before adding the XML map + if (!File.Exists(tempXsdPath)) + throw new FileNotFoundException("Temporary XSD file not found.", tempXsdPath); + + // Add the XML map to the workbook; the method returns the index of the added map + int mapIndex = workbook.Worksheets.XmlMaps.Add(tempXsdPath); + + // Retrieve the root element name of the map using the index + string rootElementName = workbook.Worksheets.XmlMaps[mapIndex].RootElementName; + + // Display the result + Console.WriteLine("Root Element Name: " + rootElementName); + + // Save the workbook (optional, demonstrates lifecycle usage) + string outputPath = "DemoOutput.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/xml-maps/retrieve-the-root-element-name-of-the-first-xml-map-via-xmlmaprootelementname-property.cs b/xml-maps/retrieve-the-root-element-name-of-the-first-xml-map-via-xmlmaprootelementname-property.cs new file mode 100644 index 0000000000..8cd181b86e --- /dev/null +++ b/xml-maps/retrieve-the-root-element-name-of-the-first-xml-map-via-xmlmaprootelementname-property.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + try + { + // Create a new workbook (creation rule) + Workbook workbook = new Workbook(); + + // Define an XML schema (XSD) that will be used to create the XML map + string xmlSchema = @" + + + + + + + + + + + + + + + "; + + // Write the schema to a temporary file because Aspose.Cells expects a file path + string tempXsdPath = Path.Combine(Path.GetTempPath(), "tempSchema.xsd"); + File.WriteAllText(tempXsdPath, xmlSchema); + + // Ensure the temporary XSD file exists before adding the XML map + if (!File.Exists(tempXsdPath)) + throw new FileNotFoundException("Temporary XSD file was not created.", tempXsdPath); + + // Add the XML map to the workbook using the temporary XSD file + int mapIndex = workbook.Worksheets.XmlMaps.Add(tempXsdPath); + + // Retrieve the first XmlMap from the collection + XmlMap firstMap = workbook.Worksheets.XmlMaps[0]; + + // Get the root element name using the RootElementName property + string rootElementName = firstMap.RootElementName; + + // Output the root element name + Console.WriteLine("Root Element Name: " + rootElementName); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + finally + { + // Clean up the temporary XSD file if it exists + try + { + string tempXsdPath = Path.Combine(Path.GetTempPath(), "tempSchema.xsd"); + if (File.Exists(tempXsdPath)) + File.Delete(tempXsdPath); + } + catch + { + // Suppress any cleanup exceptions + } + } + } +} \ No newline at end of file diff --git a/xml-maps/save-the-workbook-after-modifying-xml-maps-using-workbooksave-to-persist-changes.cs b/xml-maps/save-the-workbook-after-modifying-xml-maps-using-workbooksave-to-persist-changes.cs new file mode 100644 index 0000000000..73242bff61 --- /dev/null +++ b/xml-maps/save-the-workbook-after-modifying-xml-maps-using-workbooksave-to-persist-changes.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; + +class SaveWorkbookWithXmlMap +{ + static void Main() + { + try + { + // Create a new workbook instance + Workbook workbook = new Workbook(); + + // Define a simple XML schema that will be used for the map + string xmlSchema = @" + + + + + + + + "; + + // Write the schema to a temporary file (required by Aspose.Cells API) + string schemaPath = "SampleSchema.xsd"; + if (!File.Exists(schemaPath)) + { + File.WriteAllText(schemaPath, xmlSchema); + } + + // Add the XML map to the workbook's XmlMaps collection using the schema file path + int mapIndex = workbook.Worksheets.XmlMaps.Add(schemaPath); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + + // Modify the XML map (e.g., change its name) + xmlMap.Name = "MySampleMap"; + + // Create XmlSaveOptions and specify the map to be exported when saving + XmlSaveOptions saveOptions = new XmlSaveOptions + { + XmlMapName = xmlMap.Name + }; + + // Save the workbook; the modified XML map is persisted in the file + string outputPath = "WorkbookWithXmlMap.xml"; + workbook.Save(outputPath, saveOptions); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/xml-maps/set-a-custom-namespace-prefix-for-the-xml-map-to-handle-namespaced-xml-documents-correctly.cs b/xml-maps/set-a-custom-namespace-prefix-for-the-xml-map-to-handle-namespaced-xml-documents-correctly.cs new file mode 100644 index 0000000000..72192891df --- /dev/null +++ b/xml-maps/set-a-custom-namespace-prefix-for-the-xml-map-to-handle-namespaced-xml-documents-correctly.cs @@ -0,0 +1,81 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class XmlMapCustomNamespacePrefixDemo + { + public static void Main() + { + try + { + Run(); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + + public static void Run() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["B2"].PutValue("John Doe"); + + // XML schema with a custom namespace prefix "ns" + string xmlSchema = @" + + + + + + + + + "; + + // Add the XML map to the workbook + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + + // Set a custom name for the map (used during export) + xmlMap.Name = "ns:EmployeeMap"; + + // Export the worksheet data to an XML file using the map name + string exportPath = "EmployeeData.xml"; + + // Ensure the directory for the export file exists + string exportDir = Path.GetDirectoryName(Path.GetFullPath(exportPath)); + if (!Directory.Exists(exportDir)) + { + Directory.CreateDirectory(exportDir); + } + + workbook.ExportXml(xmlMap.Name, exportPath); + + // Save the workbook with XML mapping information + XmlSaveOptions saveOptions = new XmlSaveOptions + { + XmlMapName = xmlMap.Name // store the map name in the saved file + }; + string workbookPath = "WorkbookWithXmlMap.xlsx"; + workbook.Save(workbookPath, saveOptions); + + Console.WriteLine("XML exported to: " + exportPath); + Console.WriteLine("Workbook saved with XML map: " + workbookPath); + } + } +} \ No newline at end of file diff --git a/xml-maps/set-the-xmlmaps-preservewhitespace-property-to-true-to-keep-formatting-spaces-from-the-source-xml.cs b/xml-maps/set-the-xmlmaps-preservewhitespace-property-to-true-to-keep-formatting-spaces-from-the-source-xml.cs new file mode 100644 index 0000000000..2ec90c07bc --- /dev/null +++ b/xml-maps/set-the-xmlmaps-preservewhitespace-property-to-true-to-keep-formatting-spaces-from-the-source-xml.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class XmlMapPreserveWhitespaceDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Fill sample data + worksheet.Cells["A1"].PutValue("ID"); + worksheet.Cells["A2"].PutValue(1); + worksheet.Cells["B1"].PutValue("Name"); + worksheet.Cells["B2"].PutValue("John Doe"); + + // Define a simple XML schema for the map + string xmlSchema = @" + + + + + + + + + "; + + // Add the XML map to the workbook + int mapIndex = workbook.Worksheets.XmlMaps.Add(xmlSchema); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + + // NOTE: PreserveWhitespace property is not available in this version of Aspose.Cells. + // If needed, use the appropriate API for the version you are targeting. + + // Prepare save options for XML export + XmlSaveOptions saveOptions = new XmlSaveOptions + { + XmlMapName = xmlMap.Name, + SheetNameAsElementName = true + }; + + // Save the workbook as an XML file + string outputPath = "EmployeeData.xml"; + workbook.Save(outputPath, saveOptions); + Console.WriteLine($"Workbook saved to: {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the application + class Program + { + static void Main(string[] args) + { + XmlMapPreserveWhitespaceDemo.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/update-an-existing-xml-map-by-readding-it-with-the-same-name-and-a-new-xsd-schema.cs b/xml-maps/update-an-existing-xml-map-by-readding-it-with-the-same-name-and-a-new-xsd-schema.cs new file mode 100644 index 0000000000..115df65aa7 --- /dev/null +++ b/xml-maps/update-an-existing-xml-map-by-readding-it-with-the-same-name-and-a-new-xsd-schema.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsXmlMapUpdate +{ + class Program + { + static void Main() + { + // Paths + string workbookPath = "InputWorkbook.xlsx"; + string outputPath = "UpdatedWorkbook.xlsx"; + + // Name of the XML map to replace + string mapNameToUpdate = "MyXmlMap"; + + // New XSD schema as a string + string newXsdSchema = @" + + + + + + + + +"; + + try + { + // Verify the input workbook exists + if (!File.Exists(workbookPath)) + { + Console.WriteLine($"Error: Workbook file not found at '{workbookPath}'."); + return; + } + + // Load the workbook + Workbook workbook = new Workbook(workbookPath); + + // Access XML maps collection + XmlMapCollection xmlMaps = workbook.Worksheets.XmlMaps; + + // Find existing map index + int existingMapIndex = -1; + for (int i = 0; i < xmlMaps.Count; i++) + { + if (xmlMaps[i].Name == mapNameToUpdate) + { + existingMapIndex = i; + break; + } + } + + // Remove existing map if found + if (existingMapIndex != -1) + { + xmlMaps.RemoveAt(existingMapIndex); + } + + // Write the XSD schema to a temporary file (required by Aspose.Cells API) + string tempXsdPath = Path.Combine(Path.GetTempPath(), $"temp_{Guid.NewGuid()}.xsd"); + File.WriteAllText(tempXsdPath, newXsdSchema); + + // Add the new XML map using the temporary XSD file + int newMapIndex = xmlMaps.Add(tempXsdPath); + + // Set the desired name for the new map + XmlMap newMap = xmlMaps[newMapIndex]; + newMap.Name = mapNameToUpdate; + + // Clean up temporary XSD file + if (File.Exists(tempXsdPath)) + { + File.Delete(tempXsdPath); + } + + // Save the updated workbook + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/use-a-linq-query-on-the-workbooks-xmlmaps-collection-to-find-maps-containing-a-specific-namespace.cs b/xml-maps/use-a-linq-query-on-the-workbooks-xmlmaps-collection-to-find-maps-containing-a-specific-namespace.cs new file mode 100644 index 0000000000..44c69c715b --- /dev/null +++ b/xml-maps/use-a-linq-query-on-the-workbooks-xmlmaps-collection-to-find-maps-containing-a-specific-namespace.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Aspose.Cells; + +namespace AsposeCellsXmlMapQuery +{ + class Program + { + static void Main() + { + try + { + // Prepare dummy XSD files if they do not exist to avoid FileNotFoundException + string schemaPath1 = "schema1.xsd"; + string schemaPath2 = "schema2.xsd"; + + if (!File.Exists(schemaPath1)) + { + File.WriteAllText(schemaPath1, + @" + "); + } + + if (!File.Exists(schemaPath2)) + { + File.WriteAllText(schemaPath2, + @" + "); + } + + // Create a new workbook + Workbook workbook = new Workbook(); + + // Add XML maps with different namespaces (using local XSD files) + int mapIndex1 = workbook.Worksheets.XmlMaps.Add(schemaPath1); + XmlMap xmlMap1 = workbook.Worksheets.XmlMaps[mapIndex1]; + xmlMap1.Name = "Map1"; + + int mapIndex2 = workbook.Worksheets.XmlMaps.Add(schemaPath2); + XmlMap xmlMap2 = workbook.Worksheets.XmlMaps[mapIndex2]; + xmlMap2.Name = "Map2"; + + // Define the namespace (or part of it) to search for + string targetNamespace = "schema1.xsd"; + + // LINQ query on the XmlMaps collection to find maps containing the specific namespace + List matchingMaps = workbook.Worksheets.XmlMaps + .Cast() + .Where(m => m.DataBinding != null && + !string.IsNullOrEmpty(m.DataBinding.Url) && + m.DataBinding.Url.Contains(targetNamespace, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + // Output the results + foreach (XmlMap map in matchingMaps) + { + Console.WriteLine($"Found map: Name = {map.Name}, URL = {map.DataBinding.Url}"); + } + + // Save the workbook (output file) + workbook.Save("XmlMapNamespaceQuery.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/use-multithreading-to-process-xml-map-imports-for-several-workbooks-concurrently-improving-performance.cs b/xml-maps/use-multithreading-to-process-xml-map-imports-for-several-workbooks-concurrently-improving-performance.cs new file mode 100644 index 0000000000..1dc37a05d0 --- /dev/null +++ b/xml-maps/use-multithreading-to-process-xml-map-imports-for-several-workbooks-concurrently-improving-performance.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Aspose.Cells; + +class XmlMapImportParallel +{ + static void Main() + { + // Define the XML files to import and the corresponding output workbooks. + var jobs = new List<(string XmlPath, string OutputPath, string SheetName)> + { + ("data1.xml", "book1.xlsx", "Sheet1"), + ("data2.xml", "book2.xlsx", "Sheet1"), + ("data3.xml", "book3.xlsx", "Sheet1") + }; + + // Process each workbook concurrently. + Parallel.ForEach(jobs, job => + { + // Create a new workbook instance. + Workbook wb = new Workbook(); + + // Enable multi‑thread reading for the cells collection (optional, improves read performance). + wb.Worksheets[0].Cells.MultiThreadReading = true; + + // Import the XML data into the specified sheet starting at cell A1 (row 0, column 0). + wb.ImportXml(job.XmlPath, job.SheetName, 0, 0); + + // Save the workbook to the designated file. + wb.Save(job.OutputPath); + }); + + Console.WriteLine("All workbooks have been processed."); + } +} \ No newline at end of file diff --git a/xml-maps/use-workbookloadoptions-to-preserve-existing-xml-maps-when-opening-a-workbook-in-readonly-mode.cs b/xml-maps/use-workbookloadoptions-to-preserve-existing-xml-maps-when-opening-a-workbook-in-readonly-mode.cs new file mode 100644 index 0000000000..3397c27959 --- /dev/null +++ b/xml-maps/use-workbookloadoptions-to-preserve-existing-xml-maps-when-opening-a-workbook-in-readonly-mode.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; + +class PreserveXmlMapsReadOnly +{ + static void Main() + { + // Create LoadOptions and assign a custom LoadFilter that includes XmlMap data. + LoadOptions loadOptions = new LoadOptions(); + loadOptions.LoadFilter = new XmlMapLoadFilter(); + + // Open the workbook with the specified LoadOptions. + // This loads the workbook in a read‑only manner (no modifications are made). + Workbook workbook = new Workbook("input.xlsx", loadOptions); + + // Verify that XML maps have been preserved. + Console.WriteLine("Number of XML maps: " + workbook.Worksheets.XmlMaps.Count); + foreach (XmlMap map in workbook.Worksheets.XmlMaps) + { + Console.WriteLine($"Map Name: {map.Name}"); + } + + // Optionally save a copy of the workbook (the original XML maps remain intact). + workbook.Save("output_copy.xlsx"); + } + + // Custom LoadFilter that ensures XmlMap data is loaded together with the rest of the workbook. + private class XmlMapLoadFilter : LoadFilter + { + public override void StartSheet(Worksheet sheet) + { + // Load all sheet data and explicitly include XML maps. + LoadDataFilterOptions = LoadDataFilterOptions.All | LoadDataFilterOptions.XmlMap; + } + } +} \ No newline at end of file diff --git a/xml-maps/use-worksheetcellsfind-to-locate-a-cell-that-is-mapped-to-a-specific-xml-attribute.cs b/xml-maps/use-worksheetcellsfind-to-locate-a-cell-that-is-mapped-to-a-specific-xml-attribute.cs new file mode 100644 index 0000000000..dbbd83a235 --- /dev/null +++ b/xml-maps/use-worksheetcellsfind-to-locate-a-cell-that-is-mapped-to-a-specific-xml-attribute.cs @@ -0,0 +1,69 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; // for FindOptions enums + +namespace AsposeCellsXmlFindDemo +{ + class Program + { + static void Main() + { + try + { + // 1. Create a new workbook and get the first worksheet. + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // 2. Sample XML containing an attribute "id". + string xml = @" + + Value1 + Value2 +"; + + // 3. Import the XML into the worksheet. + // This creates an XML map automatically (default name is "Map1"). + workbook.ImportXml(xml, sheet.Name, 0, 0); + + // 4. Use the default map name created by ImportXml. + const string mapName = "Map1"; + + // 5. Link cell A1 (row 0, column 0) to the first item's "id" attribute. + // Path syntax: "/Root/Item/@id" + cells.LinkToXmlMap(mapName, 0, 0, "/Root/Item/@id"); + + // 6. Retrieve and display the linked cell's value (populated from XML). + Cell linkedCell = cells[0, 0]; + Console.WriteLine($"Linked cell initial value: {linkedCell.StringValue}"); + + // 7. Use Find to locate the cell that holds the attribute value "123". + FindOptions findOptions = new FindOptions + { + LookInType = LookInType.Values, + LookAtType = LookAtType.EntireContent, + CaseSensitive = false + }; + + Cell foundCell = cells.Find("123", null, findOptions); + if (foundCell != null) + { + Console.WriteLine($"Found cell mapped to attribute 'id' at: {foundCell.Name}"); + } + else + { + Console.WriteLine("Attribute value not found."); + } + + // 8. Save the workbook (optional). + string outputPath = "XmlAttributeFindDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {System.IO.Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/xml-maps/use-worksheetxmlmapquery-result-to-apply-background-color-formatting-to-all-cells-mapped-to-a-path.cs b/xml-maps/use-worksheetxmlmapquery-result-to-apply-background-color-formatting-to-all-cells-mapped-to-a-path.cs new file mode 100644 index 0000000000..fc81cba807 --- /dev/null +++ b/xml-maps/use-worksheetxmlmapquery-result-to-apply-background-color-formatting-to-all-cells-mapped-to-a-path.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections; +using System.Drawing; +using Aspose.Cells; + +class ApplyXmlMapBackgroundColor +{ + static void Main() + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Ensure the workbook contains at least one XML map + if (workbook.Worksheets.XmlMaps.Count == 0) + { + Console.WriteLine("No XML maps found in the workbook."); + return; + } + + // Use the first XML map (adjust index if needed) + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // Define the XML element path whose linked cells should be formatted + string xmlPath = "/Root/Item"; // <-- change to your actual path + + // Query the worksheet for cell areas linked to the specified XML path + ArrayList cellAreas = sheet.XmlMapQuery(xmlPath, xmlMap); + + // Create a style with the desired background color + Style bgStyle = workbook.CreateStyle(); + bgStyle.ForegroundColor = Color.Yellow; // background color + bgStyle.Pattern = BackgroundType.Solid; // solid fill + + // Apply the style to every cell within each returned CellArea + foreach (CellArea area in cellAreas) + { + for (int row = area.StartRow; row <= area.EndRow; row++) + { + for (int col = area.StartColumn; col <= area.EndColumn; col++) + { + Cell cell = sheet.Cells[row, col]; + cell.SetStyle(bgStyle); + } + } + } + + // Save the modified workbook + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/xml-maps/validate-linked-cells-after-importing-xml-data-by-reexecuting-worksheetxmlmapquery-and-checking-results.cs b/xml-maps/validate-linked-cells-after-importing-xml-data-by-reexecuting-worksheetxmlmapquery-and-checking-results.cs new file mode 100644 index 0000000000..d8dbf5eee6 --- /dev/null +++ b/xml-maps/validate-linked-cells-after-importing-xml-data-by-reexecuting-worksheetxmlmapquery-and-checking-results.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections; +using Aspose.Cells; + +namespace AsposeCellsXmlMapValidation +{ + public class ValidateLinkedCells + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Sample XML data to import + string xmlData = @" + + + Value1 + Value2 + +"; + + // Import the XML data into the first worksheet starting at cell A1 + // This creates an XML map automatically + workbook.ImportXml(xmlData, "Sheet1", 0, 0); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Retrieve the automatically created XML map + XmlMap xmlMap = workbook.Worksheets.XmlMaps[0]; + + // OPTIONAL: Manually link a cell to a specific XML path + // This demonstrates linking after import + worksheet.Cells.LinkToXmlMap(xmlMap.Name, 5, 0, "/Root/Data/Item"); + + // Define the XML path we want to validate + string queryPath = "/Root/Data/Item"; + + // Re‑execute the XmlMapQuery to obtain all cell areas linked to the path + ArrayList linkedAreas = worksheet.XmlMapQuery(queryPath, xmlMap); + + // Check the query result + if (linkedAreas.Count == 0) + { + Console.WriteLine($"No cells are linked to the path '{queryPath}'."); + } + else + { + Console.WriteLine($"Found {linkedAreas.Count} linked cell area(s) for path '{queryPath}':"); + + // Iterate through each CellArea and display its address and value + foreach (CellArea area in linkedAreas) + { + // For simplicity, assume each area is a single cell (StartRow/StartColumn) + string cellName = CellsHelper.CellIndexToName(area.StartRow, area.StartColumn); + string cellValue = worksheet.Cells[area.StartRow, area.StartColumn].StringValue; + + Console.WriteLine($"- Cell {cellName}: \"{cellValue}\""); + } + } + + // Save the workbook (optional, demonstrates lifecycle rule) + string outputPath = "ValidatedXmlMap.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + ValidateLinkedCells.Run(); + } + } +} \ No newline at end of file diff --git a/xml-maps/validate-the-xml-map-against-its-xsd-schema-and-report-any-validation-errors-encountered.cs b/xml-maps/validate-the-xml-map-against-its-xsd-schema-and-report-any-validation-errors-encountered.cs new file mode 100644 index 0000000000..5cf90a0d72 --- /dev/null +++ b/xml-maps/validate-the-xml-map-against-its-xsd-schema-and-report-any-validation-errors-encountered.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml; +using Aspose.Cells; + +class Program +{ + // Alias to avoid ambiguity between Aspose.Cells.ValidationType and System.Xml.ValidationType + private static readonly Type XmlValidationType = typeof(System.Xml.ValidationType); + + static void Main() + { + try + { + // XSD schema defining the XML structure + string xsd = @" + + + + + + + + + + + + + + + "; + + // Sample XML to be validated (contains an intentional error) + string xml = @" + + Item1 + 100 + + + Item2 + InvalidInteger + + "; + + // Create a workbook (no external template file used, but check if needed) + Workbook workbook = new Workbook(); + + // Add the XML map based on the XSD schema + int mapIndex = workbook.Worksheets.XmlMaps.Add(xsd); + XmlMap xmlMap = workbook.Worksheets.XmlMaps[mapIndex]; + xmlMap.Name = "DataMap"; + + // Collect validation error messages + List validationErrors = new List(); + + // Configure XML reader settings for schema validation + XmlReaderSettings settings = new XmlReaderSettings + { + // Use fully qualified enum to avoid ambiguity + ValidationType = System.Xml.ValidationType.Schema + }; + + // Load the XSD schema from the string + using (StringReader xsdReader = new StringReader(xsd)) + { + settings.Schemas.Add(null, XmlReader.Create(xsdReader)); + } + + // Capture validation events + settings.ValidationEventHandler += (sender, args) => + { + validationErrors.Add(args.Message); + }; + + // Validate the XML string against the XSD schema + using (StringReader xmlReader = new StringReader(xml)) + using (XmlReader reader = XmlReader.Create(xmlReader, settings)) + { + try + { + while (reader.Read()) { } + } + catch (XmlException ex) + { + validationErrors.Add("XML parsing error: " + ex.Message); + } + } + + // Output validation results + if (validationErrors.Count == 0) + { + Console.WriteLine("XML is valid against the XSD schema."); + } + else + { + Console.WriteLine("Validation errors encountered:"); + foreach (string error in validationErrors) + { + Console.WriteLine("- " + error); + } + } + + // Optional: export data to XML using the defined map (demonstration purpose) + // workbook.ExportXml(xmlMap.Name, "ExportedData.xml"); + } + catch (Exception ex) + { + // General exception handling to prevent runtime crashes + Console.WriteLine("An unexpected error occurred: " + ex.Message); + } + } +} \ No newline at end of file