diff --git a/workbook-merger/add-a-timestamp-worksheet-indicating-the-exact-date-and-time-of-the-merge-operation.cs b/workbook-merger/add-a-timestamp-worksheet-indicating-the-exact-date-and-time-of-the-merge-operation.cs new file mode 100644 index 0000000000..0b59f66157 --- /dev/null +++ b/workbook-merger/add-a-timestamp-worksheet-indicating-the-exact-date-and-time-of-the-merge-operation.cs @@ -0,0 +1,29 @@ +using System; +using Aspose.Cells; + +namespace MergeWithTimestampDemo +{ + public class Program + { + public static void Main() + { + // Load the first workbook (destination workbook) + Workbook destWorkbook = new Workbook("Source1.xlsx"); + + // Load the second workbook to be merged + Workbook sourceWorkbook = new Workbook("Source2.xlsx"); + + // Combine the second workbook into the destination workbook + destWorkbook.Combine(sourceWorkbook); + + // Add a new worksheet to hold the merge timestamp + Worksheet timestampSheet = destWorkbook.Worksheets.Add("MergeTimestamp"); + + // Write the exact date and time of the merge operation into cell A1 + timestampSheet.Cells["A1"].PutValue(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); + + // Save the merged workbook with the timestamp worksheet + destWorkbook.Save("MergedWithTimestamp.xlsx"); + } + } +} \ No newline at end of file diff --git a/workbook-merger/add-the-library-reference-to-a-net-project-via-nuget-before-implementing-merge-logic.cs b/workbook-merger/add-the-library-reference-to-a-net-project-via-nuget-before-implementing-merge-logic.cs new file mode 100644 index 0000000000..c581ba0fdc --- /dev/null +++ b/workbook-merger/add-the-library-reference-to-a-net-project-via-nuget-before-implementing-merge-logic.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeDemo +{ + class Program + { + static void Main(string[] args) + { + // NOTE: Before running this code, add the Aspose.Cells via NuGet: + // Install-Package Aspose.Cells + // This ensures the required library is referenced in the project. + + // Prepare sample workbooks to demonstrate merge logic. + string[] filesToMerge = new string[2]; + filesToMerge[0] = "File1.xlsx"; + filesToMerge[1] = "File2.xlsx"; + + // Create first workbook and add some data. + Workbook wb1 = new Workbook(); + wb1.Worksheets[0].Cells["A1"].PutValue("Content from File 1"); + wb1.Save(filesToMerge[0]); + + // Create second workbook and add some data. + Workbook wb2 = new Workbook(); + wb2.Worksheets[0].Cells["A1"].PutValue("Content from File 2"); + wb2.Save(filesToMerge[1]); + + // Define a temporary cached file required by CellsHelper.MergeFiles. + string cachedFile = "CacheFile.tmp"; + + // Define the destination file that will contain the merged result. + string outputFile = "MergedOutput.xlsx"; + + try + { + // Merge the source files into the destination file. + // This uses the CellsHelper.MergeFiles method as defined in the API. + CellsHelper.MergeFiles(filesToMerge, cachedFile, outputFile); + + Console.WriteLine($"Files merged successfully. Output saved to: {outputFile}"); + + // Verify the merge by loading the resulting workbook. + Workbook mergedWorkbook = new Workbook(outputFile); + Console.WriteLine("Merged workbook content:"); + Console.WriteLine($"Sheet1!A1 = {mergedWorkbook.Worksheets[0].Cells["A1"].StringValue}"); + if (mergedWorkbook.Worksheets.Count > 1) + { + Console.WriteLine($"Sheet2!A1 = {mergedWorkbook.Worksheets[1].Cells["A1"].StringValue}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error during merge: {ex.Message}"); + } + finally + { + // Clean up temporary files used for the demo. + foreach (var file in filesToMerge) + { + if (File.Exists(file)) + File.Delete(file); + } + + if (File.Exists(cachedFile)) + File.Delete(cachedFile); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/agents.md b/workbook-merger/agents.md new file mode 100644 index 0000000000..2599acbd7d --- /dev/null +++ b/workbook-merger/agents.md @@ -0,0 +1,116 @@ +--- +category: workbook-merger +framework: .NET +parent: ../agents.md +version: v2 +--- + +# Persona + +You are a C# developer specializing in workbook merging and workbook consolidation using Aspose.Cells for .NET. + +Generate simple, correct, production-quality examples that demonstrate ONE workbook-merging scenario at a time. + +--- + +# Scope + +- Standalone .cs examples +- One operation per example +- Fully runnable with dotnet run +- No external dependencies + +--- + +# Required Namespaces + +using System; +using Aspose.Cells; + +Add additional namespaces only when required. + +--- + +# Key APIs + +- Workbook +- Workbook.Combine() +- Worksheet.Copy() +- Worksheets.Add() +- SaveFormat + +--- + +# Common Pattern + +1. Create source workbooks +2. Populate sample data +3. Merge or copy worksheets +4. Save merged workbook +5. Print success message + +--- + +# Workbook Merger Rules + +- Prefer Workbook.Combine() when merging entire workbooks +- Prefer Worksheet.Copy() when merging selected worksheets +- Generate source workbooks programmatically +- Ensure merged workbook contains visible data +- One example = one merge scenario + +--- + +# Input Strategy + +- Do NOT depend on file1.xlsx or file2.xlsx +- Create sample workbooks in code +- Keep examples self-contained + +--- + +# Output Rules + +- Always generate output.xlsx +- Ensure merged workbook is saved successfully +- Output files are written to the working directory + +--- + +# Common Tasks + +- Merge two workbooks +- Merge multiple worksheets +- Copy worksheet between workbooks +- Consolidate workbook data + +--- + +# Common Mistakes + +❌ var workbook = new Workbook(); +✅ Workbook workbook = new Workbook(); + +❌ Workbook workbook = new Workbook("input.xlsx"); +✅ Workbook workbook = new Workbook(); + +❌ Merge empty workbooks +✅ Populate sample data before merging + +--- + +# Code Simplicity + +- Keep examples concise +- Avoid unnecessary helper methods +- Prefer clarity over abstraction + +--- + +# General Rules + +Refer to the root agents.md for: +- Boundaries +- Testing requirements +- Error-handling guidance +- Build and run instructions diff --git a/workbook-merger/apply-autofit-to-all-columns-in-the-merged-workbook-to-improve-readability-of-combined-data.cs b/workbook-merger/apply-autofit-to-all-columns-in-the-merged-workbook-to-improve-readability-of-combined-data.cs new file mode 100644 index 0000000000..287fe7158a --- /dev/null +++ b/workbook-merger/apply-autofit-to-all-columns-in-the-merged-workbook-to-improve-readability-of-combined-data.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class AutoFitColumnsAfterCombineDemo + { + public static void Main(string[] args) + { + try + { + string sourcePath = "SourceWorkbook.xlsx"; + string secondPath = "SecondWorkbook.xlsx"; + string outputPath = "MergedAutoFitWorkbook.xlsx"; + + // Ensure input files exist + if (!File.Exists(sourcePath)) + throw new FileNotFoundException($"Source workbook not found: {sourcePath}"); + if (!File.Exists(secondPath)) + throw new FileNotFoundException($"Second workbook not found: {secondPath}"); + + // Load workbooks + Workbook sourceWorkbook = new Workbook(sourcePath); + Workbook secondWorkbook = new Workbook(secondPath); + + // Combine the second workbook into the source workbook + sourceWorkbook.Combine(secondWorkbook); + + // AutoFit columns in each worksheet + foreach (Worksheet sheet in sourceWorkbook.Worksheets) + { + sheet.AutoFitColumns(); + } + + // Save the merged workbook + sourceWorkbook.Save(outputPath, SaveFormat.Xlsx); + Console.WriteLine($"Merged workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + // Preserve original Run method for compatibility + public static void Run() + { + Main(null); + } + } +} \ No newline at end of file diff --git a/workbook-merger/apply-autofit-to-all-rows-in-the-merged-workbook-to-ensure-proper-row-height-for-content.cs b/workbook-merger/apply-autofit-to-all-rows-in-the-merged-workbook-to-ensure-proper-row-height-for-content.cs new file mode 100644 index 0000000000..acccaad70f --- /dev/null +++ b/workbook-merger/apply-autofit-to-all-rows-in-the-merged-workbook-to-ensure-proper-row-height-for-content.cs @@ -0,0 +1,20 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Load the merged workbook (replace with actual path) + Workbook workbook = new Workbook("merged.xlsx"); + + // Apply AutoFitRows to every worksheet to adjust row heights based on content + foreach (Worksheet sheet in workbook.Worksheets) + { + sheet.AutoFitRows(); + } + + // Save the workbook after autofitting rows + workbook.Save("merged_autofit.xlsx"); + } +} \ No newline at end of file diff --git a/workbook-merger/assign-a-descriptive-title-property-to-the-merged-workbook-reflecting-the-combined-source-files.cs b/workbook-merger/assign-a-descriptive-title-property-to-the-merged-workbook-reflecting-the-combined-source-files.cs new file mode 100644 index 0000000000..ac0a2d3d76 --- /dev/null +++ b/workbook-merger/assign-a-descriptive-title-property-to-the-merged-workbook-reflecting-the-combined-source-files.cs @@ -0,0 +1,27 @@ +using System; +using Aspose.Cells; + +class MergeWorkbooksWithTitle +{ + static void Main() + { + // Paths of the source workbooks to be merged + string[] sourceFiles = { "Source1.xlsx", "Source2.xlsx" }; + + // Create an empty destination workbook + Workbook mergedWorkbook = new Workbook(); + + // Iterate through each source file, load it and combine into the destination workbook + foreach (string filePath in sourceFiles) + { + Workbook source = new Workbook(filePath); + mergedWorkbook.Combine(source); + } + + // Assign a descriptive title that reflects the combined source files + mergedWorkbook.BuiltInDocumentProperties.Title = "Combined Workbook: Source1.xlsx + Source2.xlsx"; + + // Save the merged workbook to disk + mergedWorkbook.Save("MergedWorkbook.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/workbook-merger/attach-the-merged-workbook-file-to-an-email-using-systemnetmail-after-successful-combination.cs b/workbook-merger/attach-the-merged-workbook-file-to-an-email-using-systemnetmail-after-successful-combination.cs new file mode 100644 index 0000000000..d0776ab499 --- /dev/null +++ b/workbook-merger/attach-the-merged-workbook-file-to-an-email-using-systemnetmail-after-successful-combination.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Mail; +using Aspose.Cells; + +class MergeAndEmail +{ + static void Main() + { + try + { + // Paths of the workbooks to be merged + string sourcePath1 = "Source1.xlsx"; + string sourcePath2 = "Source2.xlsx"; + + // Verify source files exist + if (!File.Exists(sourcePath1)) + throw new FileNotFoundException($"Source file not found: {sourcePath1}"); + if (!File.Exists(sourcePath2)) + throw new FileNotFoundException($"Source file not found: {sourcePath2}"); + + // Path for the merged workbook + string mergedPath = "MergedWorkbook.xlsx"; + + // Load the source workbooks + using (Workbook sourceWorkbook1 = new Workbook(sourcePath1)) + using (Workbook sourceWorkbook2 = new Workbook(sourcePath2)) + // Create an empty destination workbook + using (Workbook destWorkbook = new Workbook()) + { + // Combine the source workbooks into the destination workbook + destWorkbook.Combine(sourceWorkbook1); + destWorkbook.Combine(sourceWorkbook2); + + // Save the merged workbook + destWorkbook.Save(mergedPath, SaveFormat.Xlsx); + } + + // Email configuration (replace with valid values) + string smtpHost = "smtp.example.com"; + int smtpPort = 587; + string smtpUser = "user@example.com"; + string smtpPass = "password"; + + string fromAddress = "user@example.com"; + string toAddress = "recipient@example.com"; + string subject = "Merged Workbook"; + string body = "Please find the merged workbook attached."; + + // Create the email message + using (MailMessage mail = new MailMessage()) + { + mail.From = new MailAddress(fromAddress); + mail.To.Add(toAddress); + mail.Subject = subject; + mail.Body = body; + + // Attach the merged workbook file + if (!File.Exists(mergedPath)) + throw new FileNotFoundException($"Merged file not found: {mergedPath}"); + mail.Attachments.Add(new Attachment(mergedPath)); + + // Send the email + using (SmtpClient client = new SmtpClient(smtpHost, smtpPort)) + { + client.EnableSsl = true; + client.Credentials = new NetworkCredential(smtpUser, smtpPass); + client.Send(mail); + } + } + } + catch (FileNotFoundException fnfEx) + { + Console.Error.WriteLine($"File error: {fnfEx.Message}"); + } + catch (SmtpException smtpEx) + { + Console.Error.WriteLine($"SMTP error: {smtpEx.Message}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Unexpected error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/workbook-merger/check-that-all-charts-from-source-workbooks-appear-correctly-in-the-combined-workbook.cs b/workbook-merger/check-that-all-charts-from-source-workbooks-appear-correctly-in-the-combined-workbook.cs new file mode 100644 index 0000000000..e1ef1575ca --- /dev/null +++ b/workbook-merger/check-that-all-charts-from-source-workbooks-appear-correctly-in-the-combined-workbook.cs @@ -0,0 +1,116 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +namespace AsposeCellsChartCombineCheck +{ + class Program + { + static void Main(string[] args) + { + // Create first source workbook with a chart + Workbook sourceWorkbook1 = new Workbook(); + Worksheet sheet1 = sourceWorkbook1.Worksheets[0]; + sheet1.Name = "Source1"; + // Populate data + sheet1.Cells["A1"].PutValue("Category"); + sheet1.Cells["A2"].PutValue("A"); + sheet1.Cells["A3"].PutValue("B"); + sheet1.Cells["A4"].PutValue("C"); + sheet1.Cells["B1"].PutValue("Value"); + sheet1.Cells["B2"].PutValue(10); + sheet1.Cells["B3"].PutValue(20); + sheet1.Cells["B4"].PutValue(30); + // Add a chart + int chartIndex1 = sheet1.Charts.Add(ChartType.Column, 5, 0, 20, 8); + Chart chart1 = sheet1.Charts[chartIndex1]; + chart1.NSeries.Add("B2:B4", true); + chart1.NSeries.CategoryData = "A2:A4"; + chart1.Title.Text = "Source1 Chart"; + + // Create second source workbook with a chart + Workbook sourceWorkbook2 = new Workbook(); + Worksheet sheet2 = sourceWorkbook2.Worksheets[0]; + sheet2.Name = "Source2"; + // Populate data + sheet2.Cells["A1"].PutValue("Month"); + sheet2.Cells["A2"].PutValue("Jan"); + sheet2.Cells["A3"].PutValue("Feb"); + sheet2.Cells["A4"].PutValue("Mar"); + sheet2.Cells["B1"].PutValue("Sales"); + sheet2.Cells["B2"].PutValue(150); + sheet2.Cells["B3"].PutValue(200); + sheet2.Cells["B4"].PutValue(250); + // Add a chart + int chartIndex2 = sheet2.Charts.Add(ChartType.Line, 5, 0, 20, 8); + Chart chart2 = sheet2.Charts[chartIndex2]; + chart2.NSeries.Add("B2:B4", true); + chart2.NSeries.CategoryData = "A2:A4"; + chart2.Title.Text = "Source2 Chart"; + + // Destination workbook that will receive the combined content + Workbook destWorkbook = new Workbook(); + + // Combine both source workbooks into the destination workbook + destWorkbook.Combine(sourceWorkbook1); + destWorkbook.Combine(sourceWorkbook2); + + // Verify that all charts from the sources are present in the combined workbook + int expectedChartCount = sourceWorkbook1.Worksheets[0].Charts.Count + sourceWorkbook2.Worksheets[0].Charts.Count; + int actualChartCount = 0; + + // Iterate through all worksheets in the combined workbook and sum chart counts + foreach (Worksheet ws in destWorkbook.Worksheets) + { + actualChartCount += ws.Charts.Count; + } + + Console.WriteLine($"Expected total charts: {expectedChartCount}"); + Console.WriteLine($"Actual total charts in combined workbook: {actualChartCount}"); + + // Simple validation: compare chart types and titles + bool allChartsMatch = true; + int chartCounter = 0; + + // Helper to collect source charts in order + Chart[] sourceCharts = new Chart[] + { + chart1, + chart2 + }; + + foreach (Worksheet ws in destWorkbook.Worksheets) + { + foreach (Chart combinedChart in ws.Charts) + { + if (chartCounter >= sourceCharts.Length) + { + allChartsMatch = false; + break; + } + + Chart srcChart = sourceCharts[chartCounter]; + + // Compare type + if (combinedChart.Type != srcChart.Type) + { + allChartsMatch = false; + } + + // Compare title text + if (combinedChart.Title.Text != srcChart.Title.Text) + { + allChartsMatch = false; + } + + chartCounter++; + } + } + + Console.WriteLine($"All charts correctly transferred: {allChartsMatch}"); + + // Save the combined workbook for visual inspection (optional) + destWorkbook.Save("CombinedWorkbook.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/workbook-merger/confirm-that-embedded-images-are-retained-in-the-merged-workbook-after-using-workbookcombine.cs b/workbook-merger/confirm-that-embedded-images-are-retained-in-the-merged-workbook-after-using-workbookcombine.cs new file mode 100644 index 0000000000..dd2bdda342 --- /dev/null +++ b/workbook-merger/confirm-that-embedded-images-are-retained-in-the-merged-workbook-after-using-workbookcombine.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections; +using System.IO; +using Aspose.Cells; + +class EmbeddedImageCombineDemo +{ + static void Main() + { + try + { + // Prepare a temporary PNG image (1x1 pixel) as a byte array + byte[] pngBytes = Convert.FromBase64String( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ZcAAAAASUVORK5CYII="); + + // Write the image to a temporary file (optional, used for cleanup demonstration) + string imagePath = Path.Combine(Path.GetTempPath(), "tempImage.png"); + File.WriteAllBytes(imagePath, pngBytes); + + // Create source workbook and embed image in cell B2 + Workbook sourceWb = new Workbook(); + Worksheet sourceWs = sourceWb.Worksheets[0]; + sourceWs.Cells["B2"].EmbeddedImage = pngBytes; + sourceWs.Name = "Source"; + + // Create destination workbook and embed image in cell D4 + Workbook destWb = new Workbook(); + Worksheet destWs = destWb.Worksheets[0]; + destWs.Cells["D4"].EmbeddedImage = pngBytes; + destWs.Name = "Destination"; + + // Verify embedded images before combine + Console.WriteLine("Source workbook embedded image count: " + CountEmbeddedImages(sourceWs)); + Console.WriteLine("Destination workbook embedded image count: " + CountEmbeddedImages(destWs)); + + // Combine source into destination + destWb.Combine(sourceWb); + + // Save combined workbook + string combinedPath = Path.Combine(Path.GetTempPath(), "CombinedWorkbook.xlsx"); + destWb.Save(combinedPath, SaveFormat.Xlsx); + + // Reload combined workbook to ensure persistence + if (File.Exists(combinedPath)) + { + Workbook combinedWb = new Workbook(combinedPath); + Worksheet combinedWs = combinedWb.Worksheets[0]; + + // Verify embedded images after combine + Console.WriteLine("Combined workbook embedded image count: " + CountEmbeddedImages(combinedWs)); + } + else + { + Console.WriteLine("Combined workbook file not found: " + combinedPath); + } + + // Clean up temporary image file + if (File.Exists(imagePath)) + File.Delete(imagePath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + + // Helper method to count cells that contain embedded pictures + static int CountEmbeddedImages(Worksheet ws) + { + int count = 0; + IEnumerator enumerator = ws.Cells.GetCellsWithPlaceInCellPicture(); + while (enumerator.MoveNext()) + { + Cell cell = (Cell)enumerator.Current; + if (cell.EmbeddedImage != null && cell.EmbeddedImage.Length > 0) + count++; + } + return count; + } +} \ No newline at end of file diff --git a/workbook-merger/copy-specific-worksheets-from-source-workbooks-into-the-target-workbook-using-worksheetcopy-method.cs b/workbook-merger/copy-specific-worksheets-from-source-workbooks-into-the-target-workbook-using-worksheetcopy-method.cs new file mode 100644 index 0000000000..cfd2d35fb8 --- /dev/null +++ b/workbook-merger/copy-specific-worksheets-from-source-workbooks-into-the-target-workbook-using-worksheetcopy-method.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Load the source workbook that contains the worksheets to be copied + Workbook sourceWorkbook = new Workbook("Source.xlsx"); + + // Create a new (empty) target workbook + Workbook targetWorkbook = new Workbook(); + + // Remove the default worksheet that Aspose.Cells creates automatically + targetWorkbook.Worksheets.Clear(); + + // Define the names of the worksheets you want to copy from the source workbook + string[] worksheetsToCopy = { "Sheet1", "Data" }; + + foreach (string sheetName in worksheetsToCopy) + { + // Retrieve the source worksheet by name + Worksheet sourceSheet = sourceWorkbook.Worksheets[sheetName]; + + // Add a new blank worksheet to the target workbook with the same name + Worksheet targetSheet = targetWorkbook.Worksheets.Add(sheetName); + + // Copy the contents and formatting from the source worksheet to the target worksheet + targetSheet.Copy(sourceSheet); + } + + // Save the target workbook with the copied worksheets + targetWorkbook.Save("Target.xlsx"); + } +} \ No newline at end of file diff --git a/workbook-merger/create-a-console-application-project-in-visual-studio-to-host-the-workbook-merging-code.cs b/workbook-merger/create-a-console-application-project-in-visual-studio-to-host-the-workbook-merging-code.cs new file mode 100644 index 0000000000..af46be402e --- /dev/null +++ b/workbook-merger/create-a-console-application-project-in-visual-studio-to-host-the-workbook-merging-code.cs @@ -0,0 +1,28 @@ +using System; +using Aspose.Cells; + +namespace WorkbookMergeApp +{ + class Program + { + static void Main(string[] args) + { + // Create the source workbook and add some data + Workbook sourceWorkbook = new Workbook(); + sourceWorkbook.Worksheets[0].Cells["A1"].PutValue("Source Data"); + + // Create the destination workbook (empty) and add some data + Workbook destWorkbook = new Workbook(FileFormatType.Xlsx); + destWorkbook.Worksheets[0].Cells["B2"].PutValue("Destination Data"); + + // Merge the source workbook into the destination workbook + destWorkbook.Combine(sourceWorkbook); + + // Save the merged workbook to disk + string outputPath = "CombinedWorkbook.xlsx"; + destWorkbook.Save(outputPath, SaveFormat.Xlsx); + + Console.WriteLine($"Workbooks merged successfully. Output file: {outputPath}"); + } + } +} \ No newline at end of file diff --git a/workbook-merger/encrypt-the-merged-workbook-with-a-password-before-saving-to-protect-confidential-data.cs b/workbook-merger/encrypt-the-merged-workbook-with-a-password-before-saving-to-protect-confidential-data.cs new file mode 100644 index 0000000000..12686fe6aa --- /dev/null +++ b/workbook-merger/encrypt-the-merged-workbook-with-a-password-before-saving-to-protect-confidential-data.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsEncryptionDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (or load an existing merged workbook) + Workbook wb = new Workbook(); + + // Example: add some data to the first worksheet + Worksheet sheet = wb.Worksheets[0]; + sheet.Cells["A1"].PutValue("Confidential Data"); + + // Set the password that will be required to open the workbook + wb.Settings.Password = "StrongPassword123"; + + // (Optional) Define encryption strength – 128‑bit AES is default for modern formats + // wb.SetEncryptionOptions(EncryptionType.StrongCryptographicProvider, 128); + + // Save the encrypted workbook + wb.Save("MergedWorkbook_Encrypted.xlsx"); + + // Verify that the workbook is encrypted by loading it with the password + LoadOptions loadOptions = new LoadOptions + { + Password = "StrongPassword123" + }; + Workbook loadedWb = new Workbook("MergedWorkbook_Encrypted.xlsx", loadOptions); + Console.WriteLine("Loaded cell value: " + loadedWb.Worksheets[0].Cells["A1"].Value); + } + } +} \ No newline at end of file diff --git a/workbook-merger/ensure-formulas-remain-intact-by-keeping-calculation-mode-set-to-automatic-before-and-after-merging.cs b/workbook-merger/ensure-formulas-remain-intact-by-keeping-calculation-mode-set-to-automatic-before-and-after-merging.cs new file mode 100644 index 0000000000..7e418ed218 --- /dev/null +++ b/workbook-merger/ensure-formulas-remain-intact-by-keeping-calculation-mode-set-to-automatic-before-and-after-merging.cs @@ -0,0 +1,35 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsFormulaMergeDemo +{ + class Program + { + static void Main() + { + // Create a new workbook (creation rule) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate some data and a formula + cells["A1"].PutValue(10); + cells["A2"].PutValue(20); + cells["B1"].Formula = "=SUM(A1:A2)"; // Formula that will be affected by merging + + // Ensure calculation mode is Automatic before merging + workbook.Settings.FormulaSettings.CalculationMode = CalcModeType.Automatic; + + // Perform a merge operation (merge rule) + // Merge cells B1:C1 (row 0, column 1) spanning 1 row and 2 columns + cells.Merge(0, 1, 1, 2); + + // Verify that the calculation mode is still Automatic after merging + // (re‑apply if needed to guarantee the setting) + workbook.Settings.FormulaSettings.CalculationMode = CalcModeType.Automatic; + + // Save the workbook (save rule) + workbook.Save("FormulaMergeResult.xlsx"); + } + } +} \ No newline at end of file diff --git a/workbook-merger/export-each-worksheet-of-the-merged-workbook-to-csv-files-for-data-extraction-validation.cs b/workbook-merger/export-each-worksheet-of-the-merged-workbook-to-csv-files-for-data-extraction-validation.cs new file mode 100644 index 0000000000..1b042e33f3 --- /dev/null +++ b/workbook-merger/export-each-worksheet-of-the-merged-workbook-to-csv-files-for-data-extraction-validation.cs @@ -0,0 +1,36 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsExportEachSheetToCsv +{ + class Program + { + static void Main() + { + // Path to the merged workbook (result of previous merge operation) + string mergedWorkbookPath = "MergedOutput.xlsx"; + + // Load the merged workbook + Workbook workbook = new Workbook(mergedWorkbookPath); + + // Prepare CSV save options – ExportAllSheets is false (default) so only the active sheet is saved + TxtSaveOptions csvOptions = new TxtSaveOptions(SaveFormat.Csv); + csvOptions.ExportAllSheets = false; // ensure only the active sheet is exported + + // Export each worksheet to a separate CSV file + for (int i = 0; i < workbook.Worksheets.Count; i++) + { + // Set the current worksheet as active + workbook.Worksheets.ActiveSheetIndex = i; + + // Build a file name for the CSV (e.g., Sheet1.csv, Sheet2.csv, ...) + string csvFileName = $"Sheet{i + 1}.csv"; + + // Save the active worksheet as CSV + workbook.Save(csvFileName, csvOptions); + } + + Console.WriteLine("All worksheets have been exported to individual CSV files."); + } + } +} \ No newline at end of file diff --git a/workbook-merger/export-the-combined-workbook-to-pdf-format-to-verify-visual-fidelity-of-charts-and-images.cs b/workbook-merger/export-the-combined-workbook-to-pdf-format-to-verify-visual-fidelity-of-charts-and-images.cs new file mode 100644 index 0000000000..713c877dca --- /dev/null +++ b/workbook-merger/export-the-combined-workbook-to-pdf-format-to-verify-visual-fidelity-of-charts-and-images.cs @@ -0,0 +1,32 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsPdfExport +{ + class Program + { + static void Main() + { + // Load the first workbook (creates a Workbook instance) + Workbook combinedWorkbook = new Workbook("Workbook1.xlsx"); + + // Load the second workbook to be merged + Workbook secondWorkbook = new Workbook("Workbook2.xlsx"); + + // Combine the second workbook into the first one + combinedWorkbook.Combine(secondWorkbook); + + // Configure PDF save options (optional, e.g., export document structure) + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + ExportDocumentStructure = true + }; + + // Save the combined workbook as a PDF file + combinedWorkbook.Save("CombinedWorkbook.pdf", pdfOptions); + + Console.WriteLine("Combined workbook exported to PDF successfully."); + } + } +} \ No newline at end of file diff --git a/workbook-merger/generate-an-html-representation-of-the-merged-workbook-to-inspect-content-in-a-web-browser.cs b/workbook-merger/generate-an-html-representation-of-the-merged-workbook-to-inspect-content-in-a-web-browser.cs new file mode 100644 index 0000000000..6db02aff59 --- /dev/null +++ b/workbook-merger/generate-an-html-representation-of-the-merged-workbook-to-inspect-content-in-a-web-browser.cs @@ -0,0 +1,48 @@ +using System; +using System.Diagnostics; +using Aspose.Cells; + +namespace AsposeCellsHtmlExport +{ + class Program + { + static void Main() + { + // Create a new workbook with three worksheets + Workbook workbook = new Workbook(); + Worksheet sheet1 = workbook.Worksheets[0]; + sheet1.Name = "FirstSheet"; + sheet1.Cells["A1"].PutValue("Content of Sheet 1"); + + Worksheet sheet2 = workbook.Worksheets.Add("SecondSheet"); + sheet2.Cells["B2"].PutValue("Content of Sheet 2"); + + Worksheet sheet3 = workbook.Worksheets.Add("ThirdSheet"); + sheet3.Cells["C3"].PutValue("Content of Sheet 3"); + + // Configure HTML save options to export all sheets in a single HTML file + HtmlSaveOptions htmlOptions = new HtmlSaveOptions + { + ShowAllSheets = true, // Show every sheet + SaveAsSingleFile = true, // One HTML file only + ExportActiveWorksheetOnly = false, + ExportWorkbookProperties = true, + ExportWorksheetProperties = true, + ExportImagesAsBase64 = true // Embed images directly (if any) + }; + + // Define output path + string htmlPath = "MergedWorkbook.html"; + + // Save the workbook as HTML + workbook.Save(htmlPath, htmlOptions); + + // Open the generated HTML file in the default web browser for inspection + Process.Start(new ProcessStartInfo + { + FileName = htmlPath, + UseShellExecute = true + }); + } + } +} \ No newline at end of file diff --git a/workbook-merger/insert-a-company-logo-image-on-the-first-worksheet-of-the-merged-workbook-after-combining-files.cs b/workbook-merger/insert-a-company-logo-image-on-the-first-worksheet-of-the-merged-workbook-after-combining-files.cs new file mode 100644 index 0000000000..8b8b506acc --- /dev/null +++ b/workbook-merger/insert-a-company-logo-image-on-the-first-worksheet-of-the-merged-workbook-after-combining-files.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace InsertLogoAfterMergeApp +{ + class InsertLogoAfterMerge + { + static void Main() + { + try + { + // Paths of the workbooks that need to be merged + string[] sourceFiles = { "File1.xlsx", "File2.xlsx", "File3.xlsx" }; + + // Create an empty workbook that will hold the merged result + Workbook mergedWorkbook = new Workbook(); + + // Combine each source workbook into the destination workbook + foreach (string filePath in sourceFiles) + { + if (!File.Exists(filePath)) + { + Console.WriteLine($"Source file not found: {filePath}. Skipping."); + continue; + } + + Workbook source = new Workbook(filePath); + mergedWorkbook.Combine(source); + } + + // Insert the company logo on the first worksheet of the merged workbook + Worksheet firstSheet = mergedWorkbook.Worksheets[0]; + string logoPath = "CompanyLogo.png"; + + if (File.Exists(logoPath)) + { + // Add the picture at the top‑left corner (row 0, column 0) + firstSheet.Pictures.Add(0, 0, logoPath); + } + else + { + Console.WriteLine($"Logo file not found: {logoPath}. Skipping logo insertion."); + } + + // Save the final workbook with the inserted logo + mergedWorkbook.Save("MergedWithLogo.xlsx", SaveFormat.Xlsx); + Console.WriteLine("Merged workbook saved successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/load-large-xls-files-with-cellshelpermergefiles-by-providing-an-array-of-file-paths-and-output-path.cs b/workbook-merger/load-large-xls-files-with-cellshelpermergefiles-by-providing-an-array-of-file-paths-and-output-path.cs new file mode 100644 index 0000000000..05a2357845 --- /dev/null +++ b/workbook-merger/load-large-xls-files-with-cellshelpermergefiles-by-providing-an-array-of-file-paths-and-output-path.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeDemo +{ + class Program + { + static void Main() + { + // Paths of the large XLS files to be merged + string[] filesToMerge = new string[] + { + "LargeFile1.xls", + "LargeFile2.xls", + // Add more file paths as needed + }; + + // Temporary cache file required by CellsHelper.MergeFiles + string cacheFile = "MergeCache.tmp"; + + // Destination file where the merged result will be saved + string outputFile = "MergedLargeFiles.xls"; + + try + { + // Merge the specified files into a single workbook + CellsHelper.MergeFiles(filesToMerge, cacheFile, outputFile); + Console.WriteLine($"Files merged successfully. Output saved to: {outputFile}"); + + // Load the merged workbook to verify the operation + Workbook mergedWorkbook = new Workbook(outputFile); + Console.WriteLine($"Merged workbook contains {mergedWorkbook.Worksheets.Count} worksheet(s)."); + } + catch (Exception ex) + { + Console.WriteLine($"Error during merging: {ex.Message}"); + } + finally + { + // Clean up the temporary cache file + if (File.Exists(cacheFile)) + { + File.Delete(cacheFile); + } + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/load-source-xls-workbooks-using-new-workbookfilepath-for-each-file-to-be-merged.cs b/workbook-merger/load-source-xls-workbooks-using-new-workbookfilepath-for-each-file-to-be-merged.cs new file mode 100644 index 0000000000..cdacb1c939 --- /dev/null +++ b/workbook-merger/load-source-xls-workbooks-using-new-workbookfilepath-for-each-file-to-be-merged.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace MergeWorkbooksDemo +{ + class Program + { + static void Main() + { + try + { + // Paths of the source Excel files to be merged + string[] sourceFiles = new string[] + { + "Source1.xlsx", + "Source2.xlsx", + "Source3.xlsx" + }; + + // Create the destination workbook (empty workbook) + Workbook destinationWorkbook = new Workbook(); + + // Load each source workbook using the Workbook(string) constructor + foreach (string filePath in sourceFiles) + { + // Verify that the source file exists before loading + if (!File.Exists(filePath)) + { + Console.WriteLine($"Warning: Source file not found and will be skipped: {filePath}"); + continue; + } + + // Load source workbook + Workbook sourceWorkbook = new Workbook(filePath); + + // Combine the source workbook into the destination workbook + destinationWorkbook.Combine(sourceWorkbook); + } + + // Save the merged workbook to a new file + string outputPath = "MergedWorkbook.xlsx"; + destinationWorkbook.Save(outputPath, SaveFormat.Xlsx); + + Console.WriteLine($"Workbooks merged successfully. Output saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred during merging: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/log-the-file-size-of-the-merged-workbook-after-saving-to-monitor-storage-impact-of-the-combine-process.cs b/workbook-merger/log-the-file-size-of-the-merged-workbook-after-saving-to-monitor-storage-impact-of-the-combine-process.cs new file mode 100644 index 0000000000..774f57b97b --- /dev/null +++ b/workbook-merger/log-the-file-size-of-the-merged-workbook-after-saving-to-monitor-storage-impact-of-the-combine-process.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeAndLogSize +{ + class Program + { + static void Main() + { + // Prepare temporary files to be merged + string[] filesToMerge = new string[2]; + filesToMerge[0] = "TempFile1.xlsx"; + filesToMerge[1] = "TempFile2.xlsx"; + + // Create first workbook and save it + Workbook wb1 = new Workbook(); + wb1.Worksheets[0].Cells["A1"].PutValue("Data from first workbook"); + wb1.Save(filesToMerge[0]); // using provided Save(string) method + + // Create second workbook and save it + Workbook wb2 = new Workbook(); + wb2.Worksheets[0].Cells["A1"].PutValue("Data from second workbook"); + wb2.Save(filesToMerge[1]); // using provided Save(string) method + + // Define temporary cache file and output merged file + string cacheFile = "MergeCache.tmp"; + string mergedOutput = "MergedResult.xlsx"; + + // Merge the files using the provided CellsHelper.MergeFiles method + CellsHelper.MergeFiles(filesToMerge, cacheFile, mergedOutput); + + // After saving, obtain the file size + FileInfo mergedInfo = new FileInfo(mergedOutput); + long fileSizeInBytes = mergedInfo.Length; + + // Log the size (in kilobytes for readability) + Console.WriteLine($"Merged workbook saved to '{mergedOutput}'."); + Console.WriteLine($"File size: {fileSizeInBytes} bytes ({fileSizeInBytes / 1024.0:F2} KB)."); + + // Clean up temporary files + foreach (string path in filesToMerge) + { + if (File.Exists(path)) File.Delete(path); + } + if (File.Exists(cacheFile)) File.Delete(cacheFile); + // Optionally keep the merged file; delete if not needed + // if (File.Exists(mergedOutput)) File.Delete(mergedOutput); + } + } +} \ No newline at end of file diff --git a/workbook-merger/maintain-original-cell-formatting-by-not-altering-style-settings-during-the-combine-operation.cs b/workbook-merger/maintain-original-cell-formatting-by-not-altering-style-settings-during-the-combine-operation.cs new file mode 100644 index 0000000000..4aac1c90f6 --- /dev/null +++ b/workbook-merger/maintain-original-cell-formatting-by-not-altering-style-settings-during-the-combine-operation.cs @@ -0,0 +1,72 @@ +using System; +using System.Drawing; +using Aspose.Cells; + +namespace AsposeCellsMergePreserveStyle +{ + class Program + { + static void Main() + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate a 2x2 range with values and distinct styles + // Cell A1 + Cell a1 = cells["A1"]; + a1.PutValue("Header"); + Style styleA1 = a1.GetStyle(); + styleA1.Font.IsBold = true; + styleA1.Font.Color = Color.White; + styleA1.ForegroundColor = Color.DarkBlue; + styleA1.Pattern = BackgroundType.Solid; + a1.SetStyle(styleA1); + + // Cell B1 + Cell b1 = cells["B1"]; + b1.PutValue("SubHeader"); + Style styleB1 = b1.GetStyle(); + styleB1.Font.IsItalic = true; + styleB1.Font.Color = Color.Black; + styleB1.ForegroundColor = Color.LightGray; + styleB1.Pattern = BackgroundType.Solid; + b1.SetStyle(styleB1); + + // Cell A2 + Cell a2 = cells["A2"]; + a2.PutValue(123); + Style styleA2 = a2.GetStyle(); + styleA2.Font.Size = 12; + styleA2.Font.Color = Color.Green; + a2.SetStyle(styleA2); + + // Cell B2 + Cell b2 = cells["B2"]; + b2.PutValue(456); + Style styleB2 = b2.GetStyle(); + styleB2.Font.Size = 12; + styleB2.Font.Color = Color.Red; + b2.SetStyle(styleB2); + + // Preserve the style of the top‑left cell (A1) before merging + Style originalTopLeftStyle = a1.GetStyle(); + + // Merge the 2x2 range (A1:B2) using Cells.Merge + // Parameters: firstRow, firstColumn, totalRows, totalColumns, checkConflict, mergeConflict + // checkConflict = false (do not check for existing merges) + // mergeConflict = true (allow merging even if conflicts exist) + cells.Merge(0, 0, 2, 2, false, true); + + // After merging, reapply the original style to the merged cell. + // Using SetStyle(style, true) ensures only explicitly set properties are overwritten, + // leaving any default formatting untouched. + Cell mergedCell = cells["A1"]; // Upper‑left cell of the merged area + mergedCell.SetStyle(originalTopLeftStyle, true); + + // Save the workbook (lifecycle: save) + workbook.Save("MergedPreserveStyle.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/workbook-merger/preserve-charts-and-images-during-merge-by-employing-default-workbookcombine-behavior-without-additional-options.cs b/workbook-merger/preserve-charts-and-images-during-merge-by-employing-default-workbookcombine-behavior-without-additional-options.cs new file mode 100644 index 0000000000..1661ef9225 --- /dev/null +++ b/workbook-merger/preserve-charts-and-images-during-merge-by-employing-default-workbookcombine-behavior-without-additional-options.cs @@ -0,0 +1,21 @@ +using System; +using Aspose.Cells; + +class PreserveChartsAndImagesDuringMerge +{ + static void Main() + { + // Load the destination workbook (the one that will receive the other workbook's content) + Workbook destWorkbook = new Workbook("Destination.xlsx"); + + // Load the source workbook (the one whose content will be merged into the destination) + Workbook sourceWorkbook = new Workbook("Source.xlsx"); + + // Combine the source workbook into the destination workbook. + // The default Combine method preserves charts, images, and other objects. + destWorkbook.Combine(sourceWorkbook); + + // Save the merged workbook to a new file. + destWorkbook.Save("CombinedResult.xlsx", SaveFormat.Xlsx); + } +} \ No newline at end of file diff --git a/workbook-merger/protect-the-merged-workbook-with-a-password-to-restrict-editing-after-the-combine-operation.cs b/workbook-merger/protect-the-merged-workbook-with-a-password-to-restrict-editing-after-the-combine-operation.cs new file mode 100644 index 0000000000..da04d3d3ae --- /dev/null +++ b/workbook-merger/protect-the-merged-workbook-with-a-password-to-restrict-editing-after-the-combine-operation.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + public class ProtectMergedWorkbook + { + public static void Run() + { + try + { + const string targetPath = "Book1.xlsx"; + const string sourcePath = "Book2.xlsx"; + const string outputPath = "MergedProtected.xlsx"; + const string password = "MySecretPassword"; + + // Verify input files exist + if (!File.Exists(targetPath)) + throw new FileNotFoundException($"Target workbook not found: {targetPath}"); + if (!File.Exists(sourcePath)) + throw new FileNotFoundException($"Source workbook not found: {sourcePath}"); + + // Load workbooks + using (var mergedWorkbook = new Workbook(targetPath)) + using (var sourceWorkbook = new Workbook(sourcePath)) + { + // Copy each worksheet from source to target + foreach (Worksheet sheet in sourceWorkbook.Worksheets) + { + // AddCopy expects the source sheet name + mergedWorkbook.Worksheets.AddCopy(sheet.Name); + } + + // Protect workbook structure + mergedWorkbook.Protect(ProtectionType.Structure, password); + + // Save merged and protected workbook + mergedWorkbook.Save(outputPath, SaveFormat.Xlsx); + } + + Console.WriteLine($"Workbook merged and protected successfully: {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + public class Program + { + public static void Main(string[] args) + { + ProtectMergedWorkbook.Run(); + } + } +} \ No newline at end of file diff --git a/workbook-merger/recalculate-all-formulas-in-the-merged-workbook-by-invoking-the-calculate-method-postmerge.cs b/workbook-merger/recalculate-all-formulas-in-the-merged-workbook-by-invoking-the-calculate-method-postmerge.cs new file mode 100644 index 0000000000..c565369cdb --- /dev/null +++ b/workbook-merger/recalculate-all-formulas-in-the-merged-workbook-by-invoking-the-calculate-method-postmerge.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + class MergeAndCalculate + { + static void Main() + { + try + { + const string destPath = "Destination.xlsx"; + const string srcPath = "Source.xlsx"; + const string resultPath = "MergedResult.xlsx"; + + // Ensure input files exist + if (!File.Exists(destPath)) + { + Console.WriteLine($"File not found: {destPath}"); + return; + } + if (!File.Exists(srcPath)) + { + Console.WriteLine($"File not found: {srcPath}"); + return; + } + + // Load workbooks + Workbook destWorkbook = new Workbook(destPath); + Workbook srcWorkbook = new Workbook(srcPath); + + // Copy each worksheet from source to destination + foreach (Worksheet srcSheet in srcWorkbook.Worksheets) + { + // AddCopy expects the sheet name, not the Worksheet object + destWorkbook.Worksheets.AddCopy(srcSheet.Name); + } + + // Recalculate all formulas in the merged workbook + destWorkbook.CalculateFormula(); + + // Save the merged workbook + destWorkbook.Save(resultPath); + Console.WriteLine($"Merged workbook saved to {resultPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/save-the-merged-workbook-into-a-memory-stream-for-immediate-transmission-via-a-web-api.cs b/workbook-merger/save-the-merged-workbook-into-a-memory-stream-for-immediate-transmission-via-a-web-api.cs new file mode 100644 index 0000000000..2112e3be55 --- /dev/null +++ b/workbook-merger/save-the-merged-workbook-into-a-memory-stream-for-immediate-transmission-via-a-web-api.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace WorkbookMergeApp +{ + public class WorkbookMergeService + { + /// + /// Merges two Excel workbooks and returns the result as a MemoryStream. + /// + /// Path to the destination workbook. + /// Path to the source workbook. + /// MemoryStream containing the merged workbook (XLSX). + public MemoryStream MergeWorkbooksToStream(string firstFilePath, string secondFilePath) + { + // Verify that both files exist before attempting to load them + if (!File.Exists(firstFilePath)) + throw new FileNotFoundException($"Destination workbook not found: {firstFilePath}"); + if (!File.Exists(secondFilePath)) + throw new FileNotFoundException($"Source workbook not found: {secondFilePath}"); + + try + { + // Load the destination and source workbooks + Workbook destWorkbook = new Workbook(firstFilePath); + Workbook sourceWorkbook = new Workbook(secondFilePath); + + // Merge source workbook into destination workbook + destWorkbook.Combine(sourceWorkbook); + + // Save merged workbook into a memory stream + MemoryStream mergedStream = new MemoryStream(); + destWorkbook.Save(mergedStream, SaveFormat.Xlsx); + mergedStream.Position = 0; // Reset position for reading + + return mergedStream; + } + catch (Exception ex) + { + // Wrap any exception for clearer caller handling + throw new InvalidOperationException("Failed to merge workbooks.", ex); + } + } + } + + class Program + { + static void Main(string[] args) + { + // Example file paths – replace with actual paths as needed + string destPath = "dest.xlsx"; + string sourcePath = "source.xlsx"; + + try + { + var service = new WorkbookMergeService(); + using (MemoryStream mergedStream = service.MergeWorkbooksToStream(destPath, sourcePath)) + { + // Save the merged workbook to a physical file for verification + string outputPath = "merged.xlsx"; + using (FileStream file = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + mergedStream.CopyTo(file); + } + Console.WriteLine($"Merged workbook saved to {outputPath}"); + } + } + catch (FileNotFoundException fnfEx) + { + Console.Error.WriteLine(fnfEx.Message); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/save-the-merged-workbook-to-a-specified-output-path-using-workbooksave-method.cs b/workbook-merger/save-the-merged-workbook-to-a-specified-output-path-using-workbooksave-method.cs new file mode 100644 index 0000000000..b74a2ad4f2 --- /dev/null +++ b/workbook-merger/save-the-merged-workbook-to-a-specified-output-path-using-workbooksave-method.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeAndSaveDemo +{ + class Program + { + static void Main() + { + // Paths for the source workbooks and the final merged file + string sourcePath1 = "Source1.xlsx"; + string sourcePath2 = "Source2.xlsx"; + string mergedOutputPath = "MergedWorkbook.xlsx"; + + // ------------------------------------------------- + // Create first source workbook and add sample data + // ------------------------------------------------- + Workbook sourceWorkbook1 = new Workbook(); + Worksheet sheet1 = sourceWorkbook1.Worksheets[0]; + sheet1.Name = "FirstSheet"; + sheet1.Cells["A1"].PutValue("Data from first workbook"); + // Save to disk so it can be loaded later (optional) + sourceWorkbook1.Save(sourcePath1, SaveFormat.Xlsx); + + // ------------------------------------------------- + // Create second source workbook and add sample data + // ------------------------------------------------- + Workbook sourceWorkbook2 = new Workbook(); + Worksheet sheet2 = sourceWorkbook2.Worksheets[0]; + sheet2.Name = "SecondSheet"; + sheet2.Cells["A1"].PutValue("Data from second workbook"); + sourceWorkbook2.Save(sourcePath2, SaveFormat.Xlsx); + + // ------------------------------------------------- + // Load the two workbooks (demonstrates loading rule) + // ------------------------------------------------- + Workbook wb1 = new Workbook(sourcePath1); + Workbook wb2 = new Workbook(sourcePath2); + + // ------------------------------------------------- + // Combine the second workbook into the first one + // ------------------------------------------------- + wb1.Combine(wb2); + + // ------------------------------------------------- + // Save the merged workbook to the specified output path + // ------------------------------------------------- + wb1.Save(mergedOutputPath, SaveFormat.Xlsx); + + Console.WriteLine($"Merged workbook saved to: {Path.GetFullPath(mergedOutputPath)}"); + } + } +} \ No newline at end of file diff --git a/workbook-merger/set-the-author-property-of-the-merged-workbook-to-the-current-user-name-after-merging.cs b/workbook-merger/set-the-author-property-of-the-merged-workbook-to-the-current-user-name-after-merging.cs new file mode 100644 index 0000000000..498b59e6ca --- /dev/null +++ b/workbook-merger/set-the-author-property-of-the-merged-workbook-to-the-current-user-name-after-merging.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeAndSetAuthor +{ + class Program + { + static void Main() + { + try + { + const string primaryPath = "PrimaryWorkbook.xlsx"; + + // Verify primary workbook exists + if (!File.Exists(primaryPath)) + throw new FileNotFoundException($"Primary workbook not found: {primaryPath}"); + + // Load the primary workbook (the one that will receive the merged sheets) + Workbook mergedWorkbook = new Workbook(primaryPath); + + // Files to merge + string[] filesToMerge = { "Workbook1.xlsx", "Workbook2.xlsx" }; + + foreach (string file in filesToMerge) + { + // Skip missing files + if (!File.Exists(file)) + { + Console.WriteLine($"Warning: File not found and will be skipped: {file}"); + continue; + } + + // Load source workbook + Workbook sourceWorkbook = new Workbook(file); + + // Copy each worksheet from the source workbook into the merged workbook + foreach (Worksheet sheet in sourceWorkbook.Worksheets) + { + // Add a copy of the worksheet to the merged workbook by sheet name + mergedWorkbook.Worksheets.AddCopy(sheet.Name); + } + } + + // Set the author of the merged workbook to the current user name + mergedWorkbook.Settings.Author = Environment.UserName; + + // Save the merged workbook with the updated author property + mergedWorkbook.Save("MergedWorkbook_WithAuthor.xlsx"); + Console.WriteLine("Merge completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/set-workbook-calculation-mode-to-automatic-after-merging-to-refresh-dependent-formulas-instantly.cs b/workbook-merger/set-workbook-calculation-mode-to-automatic-after-merging-to-refresh-dependent-formulas-instantly.cs new file mode 100644 index 0000000000..c0c9dd03cc --- /dev/null +++ b/workbook-merger/set-workbook-calculation-mode-to-automatic-after-merging-to-refresh-dependent-formulas-instantly.cs @@ -0,0 +1,38 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + class SetCalculationModeAfterMerge + { + static void Main() + { + // Create a new workbook (create rule) + Workbook workbook = new Workbook(); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Add sample data + cells["A1"].PutValue(10); + cells["A2"].PutValue(20); + cells["A3"].PutValue(30); + + // Set a formula that depends on the range A1:A3 + cells["B1"].Formula = "=SUM(A1:A3)"; + + // Merge cells A1:A3 (merge rule) + sheet.Cells.Merge(0, 0, 3, 1); // rows 0-2, columns 0-0 (A1:A3) + + // After merging, set calculation mode to Automatic to refresh dependent formulas instantly + workbook.Settings.FormulaSettings.CalculationMode = CalcModeType.Automatic; + + // Force calculation of all formulas (calculate rule) + workbook.CalculateFormula(); + + // Save the workbook (save rule) + workbook.Save("MergedWorkbook.xlsx", SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/workbook-merger/use-workbookcombine-to-merge-two-or-more-workbooks-when-file-sizes-are-moderate.cs b/workbook-merger/use-workbookcombine-to-merge-two-or-more-workbooks-when-file-sizes-are-moderate.cs new file mode 100644 index 0000000000..88537224e1 --- /dev/null +++ b/workbook-merger/use-workbookcombine-to-merge-two-or-more-workbooks-when-file-sizes-are-moderate.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeDemo +{ + public class WorkbookCombineExample + { + public static void Main(string[] args) + { + try + { + Run(); + } + catch (Exception ex) + { + Console.Error.WriteLine($"An error occurred: {ex.Message}"); + } + } + + public static void Run() + { + // Destination workbook that will receive merged content + using (Workbook destWorkbook = new Workbook()) + { + // First source workbook with sample data + using (Workbook source1 = new Workbook()) + { + Worksheet sheet1 = source1.Worksheets[0]; + sheet1.Name = "Source1"; + sheet1.Cells["A1"].PutValue("Data from source workbook 1"); + sheet1.Cells["B2"].PutValue(123); + + // Merge first source into destination + destWorkbook.Combine(source1); + } + + // Second source workbook with sample data + using (Workbook source2 = new Workbook()) + { + Worksheet sheet2 = source2.Worksheets[0]; + sheet2.Name = "Source2"; + sheet2.Cells["A1"].PutValue("Data from source workbook 2"); + sheet2.Cells["C3"].PutValue(DateTime.Now); + + // Merge second source into destination + destWorkbook.Combine(source2); + } + + // Define output path + string outputPath = "CombinedWorkbook.xlsx"; + + // Ensure the directory exists before saving + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + // Save the combined workbook + destWorkbook.Save(outputPath, SaveFormat.Xlsx); + + Console.WriteLine($"Workbooks combined and saved as '{outputPath}'."); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/validate-that-no-ref-errors-exist-in-any-cell-after-merging-workbooks-with-formulas.cs b/workbook-merger/validate-that-no-ref-errors-exist-in-any-cell-after-merging-workbooks-with-formulas.cs new file mode 100644 index 0000000000..c98575411f --- /dev/null +++ b/workbook-merger/validate-that-no-ref-errors-exist-in-any-cell-after-merging-workbooks-with-formulas.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsMergeValidate +{ + class Program + { + static void Main() + { + try + { + // Create a new workbook that will hold the merged content + Workbook mergedWorkbook = new Workbook(); + + // Paths of workbooks to be merged + string[] sourceFiles = { "Source1.xlsx", "Source2.xlsx", "Source3.xlsx" }; + + // Merge each source workbook into the target workbook + foreach (string file in sourceFiles) + { + if (!File.Exists(file)) + { + Console.WriteLine($"Warning: Source file \"{file}\" not found. Skipping."); + continue; + } + + // Load source workbook + Workbook src = new Workbook(file); + + // Copy each worksheet from source to the merged workbook + foreach (Worksheet srcSheet in src.Worksheets) + { + // Add a copy of the source worksheet to the merged workbook + mergedWorkbook.Worksheets.AddCopy(srcSheet.Name); + } + } + + // Calculate all formulas in the merged workbook + mergedWorkbook.CalculateFormula(); + + // Validate that no cell contains a #REF! error after merging + bool hasRefError = false; + foreach (Worksheet sheet in mergedWorkbook.Worksheets) + { + Cells cells = sheet.Cells; + int maxRow = cells.MaxDataRow; + int maxCol = cells.MaxDataColumn; + + for (int row = 0; row <= maxRow; row++) + { + for (int col = 0; col <= maxCol; col++) + { + Cell cell = cells[row, col]; + if (cell != null && cell.StringValue == "#REF!") + { + hasRefError = true; + Console.WriteLine($"#REF! error found in sheet '{sheet.Name}' at cell {cell.Name}"); + } + } + } + } + + if (!hasRefError) + { + Console.WriteLine("Validation passed: No #REF! errors found after merging."); + } + + // Save the merged workbook + mergedWorkbook.Save("MergedOutput.xlsx"); + Console.WriteLine("Merged workbook saved as \"MergedOutput.xlsx\"."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/workbook-merger/verify-that-the-merged-workbook-contains-the-expected-number-of-worksheets-after-combination.cs b/workbook-merger/verify-that-the-merged-workbook-contains-the-expected-number-of-worksheets-after-combination.cs new file mode 100644 index 0000000000..e17cce5676 --- /dev/null +++ b/workbook-merger/verify-that-the-merged-workbook-contains-the-expected-number-of-worksheets-after-combination.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace VerifyCombinedWorkbook +{ + class Program + { + static void Main() + { + try + { + // Create source workbook and add two worksheets + Workbook sourceWorkbook = new Workbook(); + sourceWorkbook.Worksheets[0].Name = "SourceSheet1"; + + // Add a second worksheet; Add returns a Worksheet object in recent Aspose.Cells versions + Worksheet srcSheet2 = sourceWorkbook.Worksheets.Add("SourceSheet2"); + // (Optional) you can work with srcSheet2 here if needed + + // Create destination workbook and add one worksheet + Workbook destWorkbook = new Workbook(); + destWorkbook.Worksheets[0].Name = "DestSheet"; + + // Combine source into destination + destWorkbook.Combine(sourceWorkbook); + + // Expected number of worksheets after combination: + // Destination had 1, source had 2 => total should be 3 + int expectedCount = 3; + int actualCount = destWorkbook.Worksheets.Count; + + // Verify and output the result + Console.WriteLine($"Expected worksheet count: {expectedCount}"); + Console.WriteLine($"Actual worksheet count: {actualCount}"); + Console.WriteLine(actualCount == expectedCount + ? "Verification succeeded: worksheet count matches expected." + : "Verification failed: worksheet count does not match expected."); + + // Optionally save the combined workbook (demonstrates lifecycle usage) + string outputPath = "CombinedWorkbook.xlsx"; + destWorkbook.Save(outputPath, SaveFormat.Xlsx); + Console.WriteLine($"Combined workbook saved to: {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file