diff --git a/globalization-and-localization/add-subtotal-rows-to-the-worksheet-after-assigning-custom-globalizationsettings-verifying-localized-total-labels.cs b/globalization-and-localization/add-subtotal-rows-to-the-worksheet-after-assigning-custom-globalizationsettings-verifying-localized-total-labels.cs new file mode 100644 index 0000000000..5f4e0e93b4 --- /dev/null +++ b/globalization-and-localization/add-subtotal-rows-to-the-worksheet-after-assigning-custom-globalizationsettings-verifying-localized-total-labels.cs @@ -0,0 +1,80 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsSubtotalDemo +{ + // Custom globalization settings that overrides the total name for the SUM function + public class CustomGlobalizationSettings : SettableGlobalizationSettings + { + public override string GetTotalName(ConsolidationFunction functionType) + { + // Return a custom label for SUM totals; other functions use the base implementation + if (functionType == ConsolidationFunction.Sum) + return "Custom Sum Total"; + return base.GetTotalName(functionType); + } + } + + public class Program + { + public static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Populate sample data (Category | Value) + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Value"); + cells["A2"].PutValue("A"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("A"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("B"); + cells["B4"].PutValue(30); + cells["A5"].PutValue("B"); + cells["B5"].PutValue(40); + cells["A6"].PutValue("C"); + cells["B6"].PutValue(50); + + // Assign the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Define the range that contains the data (including header) + CellArea dataArea = CellArea.CreateCellArea(0, 0, 5, 1); // rows 0-5, columns 0-1 + + // Add subtotal rows: + // - Group by column 0 (Category) + // - Use SUM function + // - Apply subtotal to column 1 (Value) + // - Replace existing subtotals, no page breaks, place summary below data + cells.Subtotal( + dataArea, + groupBy: 0, + function: ConsolidationFunction.Sum, + totalList: new int[] { 1 }, + replace: true, + pageBreaks: false, + summaryBelowData: true); + + // Verify that the subtotal label uses the custom total name + // Search for the custom label in the worksheet + string customLabel = "Custom Sum Total"; + Cell foundCell = cells.Find(customLabel, null, new FindOptions() { LookInType = LookInType.Values }); + + if (foundCell != null) + { + Console.WriteLine($"Verified custom total label found at {foundCell.Name}: \"{foundCell.StringValue}\""); + } + else + { + Console.WriteLine("Custom total label not found. Verification failed."); + } + + // Save the workbook + workbook.Save("SubtotalWithCustomGlobalization.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/agents.md b/globalization-and-localization/agents.md new file mode 100644 index 0000000000..0d17b78d48 --- /dev/null +++ b/globalization-and-localization/agents.md @@ -0,0 +1,115 @@ +--- +category: globalization-and-localization +framework: .NET +parent: ../agents.md +version: v2 +--- + +# Persona + +You are a C# developer specializing in globalization, localization, regional settings, and culture-specific workbook processing using Aspose.Cells for .NET. + +Generate simple, correct, production-quality examples that demonstrate ONE globalization or localization 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 System.Globalization; +using Aspose.Cells; + +--- + +# Key APIs + +- GlobalizationSettings +- Workbook.Settings +- CultureInfo +- Style.Custom +- Cell.PutValue() + +--- + +# Common Pattern + +1. Create workbook +2. Configure culture or globalization settings +3. Add localized data +4. Format values using regional settings +5. Save workbook +6. Print success message + +--- + +# Globalization and Localization Rules + +- Demonstrate one localization feature per example +- Use CultureInfo when culture-specific behavior is required +- Use deterministic sample data +- Clearly show the effect of regional settings + +--- + +# Input Strategy + +- Do NOT rely on external XLSX files +- Generate workbook content programmatically +- Keep examples self-contained + +--- + +# Output Rules + +- Always generate output.xlsx +- Ensure workbook is saved successfully +- Output files are written to the working directory + +--- + +# Common Tasks + +- Apply culture-specific formatting +- Localize dates and numbers +- Configure globalization settings +- Work with regional formats +- Customize language-specific workbook behavior + +--- + +# Common Mistakes + +❌ var workbook = new Workbook(); +✅ Workbook workbook = new Workbook(); + +❌ Assume formatting behaves the same across cultures +✅ Explicitly configure culture settings + +❌ Workbook workbook = new Workbook("input.xlsx"); +✅ Workbook workbook = new Workbook(); + +--- + +# Code Simplicity + +- Keep examples concise +- Avoid unnecessary abstractions +- Focus on one localization capability per example + +--- + +# General Rules + +Refer to the root agents.md for: +- Boundaries +- Testing requirements +- Build and run instructions diff --git a/globalization-and-localization/apply-custom-number-format-strings-to-percentage-cells-after-loading-the-workbook-with-brazilian-portuguese-cultureinfo.cs b/globalization-and-localization/apply-custom-number-format-strings-to-percentage-cells-after-loading-the-workbook-with-brazilian-portuguese-cultureinfo.cs new file mode 100644 index 0000000000..6b222978fa --- /dev/null +++ b/globalization-and-localization/apply-custom-number-format-strings-to-percentage-cells-after-loading-the-workbook-with-brazilian-portuguese-cultureinfo.cs @@ -0,0 +1,41 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsPercentageFormatting +{ + class Program + { + static void Main() + { + // Load the workbook with Brazilian Portuguese culture (pt-BR) + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); + loadOptions.CultureInfo = new CultureInfo("pt-BR"); + Workbook workbook = new Workbook("input.xlsx", loadOptions); + + // Iterate through all cells in the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + foreach (Cell cell in cells) + { + // Retrieve the cell's style + Style style = cell.GetStyle(); + + // Check if the current style is a percentage format + if (style.IsPercent) + { + // Apply a custom percentage format that respects the culture + // "#,##0.00%" will use the culture's decimal and group separators + style.SetCustom("#,##0.00%", true); + + // Re-apply the modified style to the cell + cell.SetStyle(style); + } + } + + // Save the modified workbook + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/assign-the-custom-globalizationsettings-instance-to-workbooksettingsglobalizationsettings-before-loading-any-worksheets.cs b/globalization-and-localization/assign-the-custom-globalizationsettings-instance-to-workbooksettingsglobalizationsettings-before-loading-any-worksheets.cs new file mode 100644 index 0000000000..1cb0c3a6ae --- /dev/null +++ b/globalization-and-localization/assign-the-custom-globalizationsettings-instance-to-workbooksettingsglobalizationsettings-before-loading-any-worksheets.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; + +// Custom globalization settings derived from GlobalizationSettings +class CustomGlobalizationSettings : GlobalizationSettings +{ + // Override boolean display strings + public override string GetBooleanValueString(bool value) + { + return value ? "ИСТИНА" : "ЛОЖЬ"; + } + + // Override error value strings + public override string GetErrorValueString(string error) + { + return error switch + { + "#NAME?" => "#ИМЯ?", + "#DIV/0!" => "#ДЕЛ/0!", + "#REF!" => "#ССЫЛКА!", + "#VALUE!" => "#ЗНАЧ!", + "#N/A" => "#Н/Д", + "#NUM!" => "#ЧИСЛО!", + "#NULL!" => "#ПУСТО!", + _ => base.GetErrorValueString(error) + }; + } +} + +class Program +{ + static void Main() + { + // Create LoadOptions (no special options needed for this example) + LoadOptions loadOptions = new LoadOptions(); + + // Load the workbook; at this point no worksheet has been accessed yet + Workbook workbook = new Workbook("input.xlsx", loadOptions); + + // Assign the custom globalization settings BEFORE any worksheet is accessed + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Now worksheets can be used safely with the custom settings applied + Worksheet sheet = workbook.Worksheets[0]; + Cell cell = sheet.Cells["A1"]; + Console.WriteLine($"Cell[0,0] value: {cell.StringValue}"); + + // Save the workbook if needed + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/assign-the-custom-globalizationsettings-to-the-workbook-before-adding-subtotals-to-ensure-localized-labels.cs b/globalization-and-localization/assign-the-custom-globalizationsettings-to-the-workbook-before-adding-subtotals-to-ensure-localized-labels.cs new file mode 100644 index 0000000000..13ffa15f3b --- /dev/null +++ b/globalization-and-localization/assign-the-custom-globalizationsettings-to-the-workbook-before-adding-subtotals-to-ensure-localized-labels.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Amount"); + cells["A2"].PutValue("A"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("A"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("B"); + cells["B4"].PutValue(30); + cells["A5"].PutValue("B"); + cells["B5"].PutValue(40); + + // Assign custom globalization settings before adding subtotals + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Define the range for subtotal (rows 0‑4, columns 0‑1) + CellArea area = CellArea.CreateCellArea(0, 0, 4, 1); + + // Add subtotal: group by column 0 (Category) and calculate Sum on column 1 (Amount) + // Parameters: area, columnIndexToGroup, function, columnsToSubtotal, replace, pageBreaks, summaryBelowData + cells.Subtotal(area, 0, ConsolidationFunction.Sum, new int[] { 1 }, true, false, true); + + // Save the workbook + workbook.Save("CustomGlobalizationSubtotal.xlsx"); + } + + // Custom globalization settings to provide localized total label + class CustomGlobalizationSettings : GlobalizationSettings + { + public override string GetTotalName(ConsolidationFunction functionType) + { + // Return a custom label for the Sum total; fall back to default for others + return functionType == ConsolidationFunction.Sum + ? "Custom Sum Total" + : base.GetTotalName(functionType); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/batch-process-a-folder-of-xlsx-files-loading-each-with-spanish-cultureinfo-and-exporting-charts-to-png-images.cs b/globalization-and-localization/batch-process-a-folder-of-xlsx-files-loading-each-with-spanish-cultureinfo-and-exporting-charts-to-png-images.cs new file mode 100644 index 0000000000..06d51da411 --- /dev/null +++ b/globalization-and-localization/batch-process-a-folder-of-xlsx-files-loading-each-with-spanish-cultureinfo-and-exporting-charts-to-png-images.cs @@ -0,0 +1,66 @@ +using System; +using System.Globalization; +using System.IO; +using Aspose.Cells; + +class BatchChartExport +{ + static void Main() + { + // Folder containing the source XLSX files + string inputFolder = @"C:\InputXlsx"; + // Folder where the PNG images will be saved + string outputFolder = @"C:\OutputPng"; + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Spanish culture (es-ES) to be used while loading workbooks + CultureInfo spanishCulture = new CultureInfo("es-ES"); + + // Process each .xlsx file in the input folder + foreach (string filePath in Directory.GetFiles(inputFolder, "*.xlsx")) + { + // Create LoadOptions with Spanish culture + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); + loadOptions.CultureInfo = spanishCulture; + + // Load the workbook using the constructor rule: Workbook(string, LoadOptions) + Workbook workbook = new Workbook(filePath, loadOptions); + + // Iterate through all worksheets + for (int wsIndex = 0; wsIndex < workbook.Worksheets.Count; wsIndex++) + { + var worksheet = workbook.Worksheets[wsIndex]; + + // Iterate through all charts in the worksheet + for (int chartIndex = 0; chartIndex < worksheet.Charts.Count; chartIndex++) + { + var chart = worksheet.Charts[chartIndex]; + + // Determine a safe file name for the chart image + string chartName = string.IsNullOrEmpty(chart.Name) + ? $"Chart_{wsIndex}_{chartIndex}" + : chart.Name; + string safeChartName = MakeSafeFileName(chartName); + + // Build the output PNG file path + string outputFile = Path.Combine( + outputFolder, + $"{Path.GetFileNameWithoutExtension(filePath)}_{safeChartName}.png"); + + // Export the chart to PNG (free‑form code – no rule exists for this operation) + chart.ToImage(outputFile); + } + } + } + } + + // Helper to replace invalid filename characters + static string MakeSafeFileName(string name) + { + foreach (char c in Path.GetInvalidFileNameChars()) + name = name.Replace(c, '_'); + return name; + } +} \ No newline at end of file diff --git a/globalization-and-localization/compare-pdf-output-of-a-workbook-loaded-with-invariant-culture-versus-french-culture-to-assess-number-format-differences.cs b/globalization-and-localization/compare-pdf-output-of-a-workbook-loaded-with-invariant-culture-versus-french-culture-to-assess-number-format-differences.cs new file mode 100644 index 0000000000..a05e2a1b8a --- /dev/null +++ b/globalization-and-localization/compare-pdf-output-of-a-workbook-loaded-with-invariant-culture-versus-french-culture-to-assess-number-format-differences.cs @@ -0,0 +1,67 @@ +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using Aspose.Cells; + +namespace AsposeCellsCulturePdfComparison +{ + class Program + { + static void Main() + { + // Step 1: Create a sample workbook with numeric data and a custom number format. + Workbook sampleWorkbook = new Workbook(); + Worksheet sheet = sampleWorkbook.Worksheets[0]; + // Populate some numbers. + sheet.Cells["A1"].PutValue(1234.56); + sheet.Cells["A2"].PutValue(7890.12); + sheet.Cells["A3"].PutValue(3456.78); + // Apply a number format that uses group and decimal separators. + Style numberStyle = sampleWorkbook.CreateStyle(); + numberStyle.Custom = "#,##0.00"; + sheet.Cells["A1"].SetStyle(numberStyle); + sheet.Cells["A2"].SetStyle(numberStyle); + sheet.Cells["A3"].SetStyle(numberStyle); + + // Save the workbook to a temporary XLSX file (used as the source for both loads). + string sourcePath = "sample.xlsx"; + sampleWorkbook.Save(sourcePath, SaveFormat.Xlsx); + + // Step 2: Load the workbook with InvariantCulture and export to PDF. + LoadOptions invariantOptions = new LoadOptions(LoadFormat.Xlsx); + invariantOptions.CultureInfo = CultureInfo.InvariantCulture; + Workbook wbInvariant = new Workbook(sourcePath, invariantOptions); + string pdfInvariantPath = "output_invariant.pdf"; + wbInvariant.Save(pdfInvariantPath, SaveFormat.Pdf); + + // Step 3: Load the workbook with French culture (fr-FR) and export to PDF. + LoadOptions frenchOptions = new LoadOptions(LoadFormat.Xlsx); + frenchOptions.CultureInfo = new CultureInfo("fr-FR"); + Workbook wbFrench = new Workbook(sourcePath, frenchOptions); + string pdfFrenchPath = "output_french.pdf"; + wbFrench.Save(pdfFrenchPath, SaveFormat.Pdf); + + // Step 4: Compare the two PDF files byte‑by‑byte. + byte[] pdfInvariantBytes = File.ReadAllBytes(pdfInvariantPath); + byte[] pdfFrenchBytes = File.ReadAllBytes(pdfFrenchPath); + bool pdfsAreIdentical = pdfInvariantBytes.SequenceEqual(pdfFrenchBytes); + + Console.WriteLine($"PDFs are {(pdfsAreIdentical ? "identical" : "different")}."); + + // Optional: Show a simple metric of difference (number of differing bytes). + if (!pdfsAreIdentical) + { + int diffCount = pdfInvariantBytes.Zip(pdfFrenchBytes, (b1, b2) => b1 == b2 ? 0 : 1).Sum(); + // Account for length differences. + diffCount += Math.Abs(pdfInvariantBytes.Length - pdfFrenchBytes.Length); + Console.WriteLine($"Number of differing bytes: {diffCount}"); + } + + // Cleanup temporary files (optional). + // File.Delete(sourcePath); + // File.Delete(pdfInvariantPath); + // File.Delete(pdfFrenchPath); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/configure-chart-rendering-to-use-antialiasing-while-applying-custom-chartglobalizationsettings-for-improved-visual-quality.cs b/globalization-and-localization/configure-chart-rendering-to-use-antialiasing-while-applying-custom-chartglobalizationsettings-for-improved-visual-quality.cs new file mode 100644 index 0000000000..0930d9d554 --- /dev/null +++ b/globalization-and-localization/configure-chart-rendering-to-use-antialiasing-while-applying-custom-chartglobalizationsettings-for-improved-visual-quality.cs @@ -0,0 +1,76 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +namespace AsposeCellsChartAntiAliasDemo +{ + // Custom globalization settings for charts + public class CustomChartGlobalizationSettings : ChartGlobalizationSettings + { + // Override chart title text + public override string GetChartTitleName() + { + return "Custom Chart Title"; + } + + // Override axis unit name for demonstration + public override string GetAxisUnitName(DisplayUnitType type) + { + return type switch + { + DisplayUnitType.Hundreds => "Hundreds", + DisplayUnitType.Thousands => "Thousands", + DisplayUnitType.TenThousands => "Ten Thousands", + _ => base.GetAxisUnitName(type) + }; + } + } + + public class Program + { + public static void Main() + { + try + { + // Create a new workbook and get the first worksheet + Workbook wb = new Workbook(); + Worksheet ws = wb.Worksheets[0]; + + // Populate sample data for the chart + ws.Cells["A1"].PutValue("Category"); + ws.Cells["B1"].PutValue("Value"); + ws.Cells["A2"].PutValue("Q1"); + ws.Cells["A3"].PutValue("Q2"); + ws.Cells["A4"].PutValue("Q3"); + ws.Cells["B2"].PutValue(120); + ws.Cells["B3"].PutValue(150); + ws.Cells["B4"].PutValue(180); + + // Add a column chart + int chartIdx = ws.Charts.Add(ChartType.Column, 5, 0, 15, 10); + Chart chart = ws.Charts[chartIdx]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + + // Apply custom chart globalization settings + wb.Settings.GlobalizationSettings = new GlobalizationSettings + { + ChartSettings = new CustomChartGlobalizationSettings() + }; + + // Render the chart to a PNG image file (default format is PNG) + string chartImagePath = "RenderedChart.png"; + chart.ToImage(chartImagePath); + + // Save the workbook + string workbookPath = "WorkbookWithChart.xlsx"; + wb.Save(workbookPath); + } + catch (Exception ex) + { + // Log or handle exceptions as needed + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/configure-workbook-to-use-a-specific-cultureinfo-object-for-date-and-number-formats-during-localization.cs b/globalization-and-localization/configure-workbook-to-use-a-specific-cultureinfo-object-for-date-and-number-formats-during-localization.cs new file mode 100644 index 0000000000..c8ba5f8bd1 --- /dev/null +++ b/globalization-and-localization/configure-workbook-to-use-a-specific-cultureinfo-object-for-date-and-number-formats-during-localization.cs @@ -0,0 +1,40 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Configure the workbook to use a specific culture (German - Germany) + // This affects date and number formatting throughout the workbook + workbook.Settings.CultureInfo = new CultureInfo("de-DE"); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Demonstrate number formatting with the specified culture + Cell numberCell = sheet.Cells["A1"]; + numberCell.PutValue(1234567.89); // Put a numeric value + + // Apply a built‑in number format (currency) which will be rendered using German conventions + Style numberStyle = numberCell.GetStyle(); + numberStyle.Number = 4; // Currency format + numberCell.SetStyle(numberStyle); + + // Demonstrate date formatting with the specified culture + Cell dateCell = sheet.Cells["A2"]; + dateCell.PutValue(DateTime.Now); // Put the current date/time + + // Apply a built‑in date format which will be rendered using German conventions + Style dateStyle = dateCell.GetStyle(); + dateStyle.Number = 14; // Short date format + dateCell.SetStyle(dateStyle); + + // Save the workbook to a file + workbook.Save("LocalizedWorkbook.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/convert-gregorian-date-cells-to-japanese-calendar-dates-with-cellshelper-preserving-era-information-for-each-cell.cs b/globalization-and-localization/convert-gregorian-date-cells-to-japanese-calendar-dates-with-cellshelper-preserving-era-information-for-each-cell.cs new file mode 100644 index 0000000000..b050f2b3b2 --- /dev/null +++ b/globalization-and-localization/convert-gregorian-date-cells-to-japanese-calendar-dates-with-cellshelper-preserving-era-information-for-each-cell.cs @@ -0,0 +1,57 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsJapaneseDateConversion +{ + class Program + { + static void Main() + { + // Load an existing workbook (replace with your actual file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Get the first worksheet (adjust as needed) + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Prepare Japanese culture with JapaneseCalendar + CultureInfo jpCulture = new CultureInfo("ja-JP"); + jpCulture.DateTimeFormat.Calendar = new JapaneseCalendar(); + + // Iterate through all used cells in the worksheet + 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]; + + // Process only cells that contain a date value + if (cell.Type == CellValueType.IsDateTime) + { + // Convert the Excel serial number to DateTime using CellsHelper + double serial = cell.DoubleValue; + DateTime date = CellsHelper.GetDateTimeFromDouble(serial, workbook.Settings.Date1904); + + // Format the date using Japanese calendar (e.g., "平成31年4月30日") + string formatted = date.ToString("gg y年M月d日", jpCulture); + + // Replace the cell value with the formatted Japanese date string + cell.PutValue(formatted); + + // Ensure the cell is treated as text to preserve the era string + Style style = cell.GetStyle(); + style.Number = 0; // General format (text) + cell.SetStyle(style); + } + } + } + + // Save the modified workbook + workbook.Save("output.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-batch-process-that-applies-the-custom-globalization-settings-to-all-workbooks-in-a-folder.cs b/globalization-and-localization/create-a-batch-process-that-applies-the-custom-globalization-settings-to-all-workbooks-in-a-folder.cs new file mode 100644 index 0000000000..14eeb10b31 --- /dev/null +++ b/globalization-and-localization/create-a-batch-process-that-applies-the-custom-globalization-settings-to-all-workbooks-in-a-folder.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsBatchGlobalization +{ + // Custom batch processor that applies globalization settings to every workbook in a folder + public static class GlobalizationBatchProcessor + { + // Entry point + public static void ProcessFolder(string inputFolder, string outputFolder) + { + // Ensure output folder exists + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + + // Get all Excel files (you can adjust the pattern as needed) + string[] files = Directory.GetFiles(inputFolder, "*.xlsx", SearchOption.TopDirectoryOnly); + + foreach (string filePath in files) + { + // Load the workbook (uses the provided load rule) + using (Workbook workbook = new Workbook(filePath)) + { + // Create and configure custom globalization settings (uses the provided create rule) + SettableGlobalizationSettings gSettings = new SettableGlobalizationSettings(); + + // Example customizations + gSettings.SetListSeparator(';'); // Use semicolon as list separator + gSettings.SetBooleanValueString(true, "TRUE_CUSTOM"); // Custom true string + gSettings.SetBooleanValueString(false, "FALSE_CUSTOM"); // Custom false string + gSettings.SetLocalFunctionName("SUM", "SUMME", true); // Localized SUM function (German) + gSettings.SetLocalFunctionName("AVERAGE", "MITTELWERT", true); // Localized AVERAGE + + // Apply the settings to the workbook + workbook.Settings.GlobalizationSettings = gSettings; + + // Determine output path (same name, different folder) + string outputPath = Path.Combine(outputFolder, Path.GetFileName(filePath)); + + // Save the modified workbook (uses the provided save rule) + workbook.Save(outputPath); + } + } + } + } + + // Example usage + class Program + { + static void Main() + { + string sourceFolder = @"C:\InputWorkbooks"; + string destinationFolder = @"C:\OutputWorkbooks"; + + GlobalizationBatchProcessor.ProcessFolder(sourceFolder, destinationFolder); + + Console.WriteLine("Batch processing completed."); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-configuration-file-mapping-locale-identifiers-to-corresponding-custom-globalizationsettings-classes.cs b/globalization-and-localization/create-a-configuration-file-mapping-locale-identifiers-to-corresponding-custom-globalizationsettings-classes.cs new file mode 100644 index 0000000000..a30624ba36 --- /dev/null +++ b/globalization-and-localization/create-a-configuration-file-mapping-locale-identifiers-to-corresponding-custom-globalizationsettings-classes.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Aspose.Cells; + +namespace AsposeCellsLocaleConfig +{ + // Base class for custom globalization settings (inherits from Aspose.Cells.GlobalizationSettings) + public abstract class CustomGlobalizationSettingsBase : GlobalizationSettings + { + // Common helper can be added here if needed + } + + // Example custom settings for English (US) + public class EnglishGlobalizationSettings : CustomGlobalizationSettingsBase + { + public override string GetBooleanValueString(bool bv) + { + return bv ? "TRUE_EN" : "FALSE_EN"; + } + } + + // Example custom settings for Russian + public class RussianGlobalizationSettings : CustomGlobalizationSettingsBase + { + public override string GetBooleanValueString(bool bv) + { + return bv ? "ИСТИНА" : "ЛОЖЬ"; + } + + public override string GetErrorValueString(string err) + { + return err switch + { + "#NAME?" => "#ИМЯ?", + "#DIV/0!" => "#ДЕЛ/0!", + "#REF!" => "#ССЫЛКА!", + "#VALUE!" => "#ЗНАЧ?", + "#N/A" => "#Н/Д", + "#NUM!" => "#ЧИСЛО!", + "#NULL!" => "#ПУСТО!", + _ => base.GetErrorValueString(err) + }; + } + } + + // Factory that reads a configuration file and provides the appropriate GlobalizationSettings instance + public static class GlobalizationSettingsFactory + { + // Mapping from LCID to the Type of the custom settings class + private static readonly Dictionary _localeTypeMap = new Dictionary(); + + // Load mapping from a JSON configuration file. + // The JSON should be an object where keys are LCIDs (as strings) and values are the fully qualified type names. + // Example: { "1033": "AsposeCellsLocaleConfig.EnglishGlobalizationSettings", "1049": "AsposeCellsLocaleConfig.RussianGlobalizationSettings" } + public static void LoadConfiguration(string configFilePath) + { + if (!File.Exists(configFilePath)) + throw new FileNotFoundException($"Configuration file not found: {configFilePath}"); + + string json = File.ReadAllText(configFilePath); + var rawMap = JsonSerializer.Deserialize>(json); + + _localeTypeMap.Clear(); + + foreach (var kvp in rawMap) + { + if (!int.TryParse(kvp.Key, out int lcid)) + continue; // skip invalid keys + + // Resolve the type by name + Type type = Type.GetType(kvp.Value, throwOnError: false, ignoreCase: true); + if (type != null && typeof(GlobalizationSettings).IsAssignableFrom(type)) + { + _localeTypeMap[lcid] = type; + } + } + } + + // Retrieve an instance of the appropriate GlobalizationSettings for the given LCID. + // If no custom mapping exists, returns the default GlobalizationSettings instance. + public static GlobalizationSettings GetSettings(int lcid) + { + if (_localeTypeMap.TryGetValue(lcid, out Type settingsType)) + { + // Use Activator to create an instance (must have a parameterless constructor) + return (GlobalizationSettings)Activator.CreateInstance(settingsType); + } + + // Fallback to default settings + return new GlobalizationSettings(); + } + } + + // Demonstration of using the factory to apply locale‑specific globalization settings to a workbook + public class Demo + { + public static void Run() + { + try + { + // Path to the JSON configuration file + string configPath = "localeConfig.json"; + + // If the config file does not exist, create a default one + if (!File.Exists(configPath)) + { + var defaultConfig = new Dictionary + { + { "1033", "AsposeCellsLocaleConfig.EnglishGlobalizationSettings" }, + { "1049", "AsposeCellsLocaleConfig.RussianGlobalizationSettings" } + }; + string defaultJson = JsonSerializer.Serialize(defaultConfig, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(configPath, defaultJson); + } + + // Load the mapping (ensure the file exists with proper content) + GlobalizationSettingsFactory.LoadConfiguration(configPath); + + // Example: choose a locale identifier (LCID). 1049 = Russian, 1033 = English (US) + int localeId = 1049; + + // Obtain the appropriate globalization settings instance + GlobalizationSettings localeSettings = GlobalizationSettingsFactory.GetSettings(localeId); + + // Create a new workbook and apply the settings + Workbook wb = new Workbook(); + wb.Settings.GlobalizationSettings = localeSettings; + + // Populate some sample data to illustrate the effect + Worksheet ws = wb.Worksheets[0]; + ws.Cells["A1"].PutValue(true); // Boolean value + ws.Cells["A2"].PutValue("#DIV/0!"); // Error value + + // Save the workbook + string outputPath = "LocalizedWorkbook.xlsx"; + wb.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error during demo execution: {ex.Message}"); + } + } + } + + // Entry point + class Program + { + static void Main() + { + Demo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-custom-globalizationsettings-class-overriding-getlocalfunctionname-for-target-language-functions.cs b/globalization-and-localization/create-a-custom-globalizationsettings-class-overriding-getlocalfunctionname-for-target-language-functions.cs new file mode 100644 index 0000000000..4cac52c253 --- /dev/null +++ b/globalization-and-localization/create-a-custom-globalizationsettings-class-overriding-getlocalfunctionname-for-target-language-functions.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsCustomGlobalizationDemo +{ + // Custom globalization settings that maps standard function names to localized ones. + public class CustomGlobalizationSettings : GlobalizationSettings + { + // Override to provide locale‑dependent function names. + public override string GetLocalFunctionName(string standardName) + { + // Map the standard "SUM" function to a custom localized name "LOCALSUM". + if (standardName.Equals("SUM", StringComparison.OrdinalIgnoreCase)) + return "LOCALSUM"; + + // Map the standard "AVERAGE" function to a custom localized name "LOCALAVERAGE". + if (standardName.Equals("AVERAGE", StringComparison.OrdinalIgnoreCase)) + return "LOCALAVERAGE"; + + // For all other functions fall back to the base implementation. + return base.GetLocalFunctionName(standardName); + } + } + + class Program + { + static void Main() + { + try + { + // Create a new workbook and get the first worksheet. + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Assign the custom globalization settings to the workbook. + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // NOTE: In recent Aspose.Cells versions, function localization is enabled by default. + // If using an older version where explicit enabling is required, uncomment the following line: + // workbook.Settings.CalcEngineSettings.EnableFunctionLocalization = true; + + // Populate sample data that will be summed. + worksheet.Cells["B1"].PutValue(5); + worksheet.Cells["B2"].PutValue(15); + worksheet.Cells["B3"].PutValue(25); + + // Use the localized function name in a formula. + Cell formulaCell = worksheet.Cells["B4"]; + formulaCell.Formula = "=LOCALSUM(B1:B3)"; + + // Calculate the formula. + workbook.CalculateFormula(); + + // Output the result to the console. + Console.WriteLine($"Result of LOCALSUM(B1:B3): {formulaCell.DoubleValue}"); + + // Save the workbook to a file. + string outputPath = "CustomGlobalizationDemo.xlsx"; + + // Ensure the directory exists before saving. + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-diagnostic-tool-that-compares-original-english-formulas-with-localized-versions-for-accuracy-verification.cs b/globalization-and-localization/create-a-diagnostic-tool-that-compares-original-english-formulas-with-localized-versions-for-accuracy-verification.cs new file mode 100644 index 0000000000..ffee89bf06 --- /dev/null +++ b/globalization-and-localization/create-a-diagnostic-tool-that-compares-original-english-formulas-with-localized-versions-for-accuracy-verification.cs @@ -0,0 +1,110 @@ +using System; +using System.IO; +using Aspose.Cells; +using CellsRange = Aspose.Cells.Range; // Alias to avoid conflict with System.Range + +namespace FormulaLocalizationDiagnostic +{ + public class DiagnosticTool + { + // Runs the diagnostic: loads a workbook, compares English and localized formulas, + // writes the comparison to a new worksheet, and saves the result. + public static void Run(string inputPath, string outputPath) + { + try + { + // Verify input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Error: Input file '{inputPath}' not found."); + return; + } + + // Load the workbook from the specified file + Workbook workbook = new Workbook(inputPath); + + // Create a new worksheet to store diagnostic results + Worksheet diagSheet = workbook.Worksheets[workbook.Worksheets.Add()]; + diagSheet.Name = "FormulaDiagnostic"; + + // Write header row + diagSheet.Cells["A1"].PutValue("Sheet"); + diagSheet.Cells["B1"].PutValue("Cell"); + diagSheet.Cells["C1"].PutValue("English Formula"); + diagSheet.Cells["D1"].PutValue("Localized Formula"); + diagSheet.Cells["E1"].PutValue("Match (English=Localized)"); + + int outputRow = 1; // zero‑based index; start after header + + // Iterate through all worksheets and cells + foreach (Worksheet ws in workbook.Worksheets) + { + // Skip the diagnostic sheet itself + if (ws.Name == diagSheet.Name) continue; + + // Get the used range to limit iteration + CellsRange usedRange = ws.Cells.MaxDisplayRange; + if (usedRange == null) continue; + + int firstRow = usedRange.FirstRow; + int lastRow = usedRange.FirstRow + usedRange.RowCount - 1; + int firstCol = usedRange.FirstColumn; + int lastCol = usedRange.FirstColumn + usedRange.ColumnCount - 1; + + for (int row = firstRow; row <= lastRow; row++) + { + for (int col = firstCol; col <= lastCol; col++) + { + Cell cell = ws.Cells[row, col]; + + // Process only cells that contain a formula + if (!string.IsNullOrEmpty(cell.Formula)) + { + string englishFormula = cell.Formula; // Standard (en‑US) formula + string localizedFormula = cell.FormulaLocal; // Locale‑specific formula + + bool match = string.Equals(englishFormula, localizedFormula, StringComparison.OrdinalIgnoreCase); + + // Write the comparison data to the diagnostic sheet + diagSheet.Cells[outputRow, 0].PutValue(ws.Name); + diagSheet.Cells[outputRow, 1].PutValue(cell.Name); + diagSheet.Cells[outputRow, 2].PutValue(englishFormula); + diagSheet.Cells[outputRow, 3].PutValue(localizedFormula); + diagSheet.Cells[outputRow, 4].PutValue(match ? "Yes" : "No"); + + outputRow++; + } + } + } + } + + // Auto‑fit columns for readability + diagSheet.AutoFitColumns(); + + // Save the workbook with diagnostics + workbook.Save(outputPath); + Console.WriteLine($"Diagnostic completed. Results saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred during diagnostic: {ex.Message}"); + } + } + + // Example usage + public static void Main(string[] args) + { + // Ensure two arguments: input file path and output file path + if (args.Length != 2) + { + Console.WriteLine("Usage: FormulaLocalizationDiagnostic "); + return; + } + + string inputFile = args[0]; + string outputFile = args[1]; + + Run(inputFile, outputFile); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-function-that-returns-a-formatted-japanese-era-date-string-given-a-gregorian-datetime-input.cs b/globalization-and-localization/create-a-function-that-returns-a-formatted-japanese-era-date-string-given-a-gregorian-datetime-input.cs new file mode 100644 index 0000000000..42f7250901 --- /dev/null +++ b/globalization-and-localization/create-a-function-that-returns-a-formatted-japanese-era-date-string-given-a-gregorian-datetime-input.cs @@ -0,0 +1,54 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsJapaneseEra +{ + public static class JapaneseEraFormatter + { + /// + /// Returns a formatted Japanese era date string for the specified Gregorian DateTime. + /// + /// Gregorian date to format. + /// Japanese era formatted date string. + public static string GetJapaneseEraDateString(DateTime date) + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + + // Set the workbook region to Japan to ensure Japanese locale handling + workbook.Settings.Region = CountryCode.Japan; + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Put the Gregorian date into a cell + Cell cell = sheet.Cells["A1"]; + cell.PutValue(date); + + // Apply a custom number format that includes the Japanese era (gengō) + // Format: era name (gg), era year (e), followed by year, month, day in Japanese characters + Style style = cell.GetStyle(); + style.Custom = "[$-ja-JP]ggge年M月d日"; + cell.SetStyle(style); + + // Retrieve the formatted string value from the cell + string formattedDate = cell.StringValue; + + // Optionally, clean up resources (save not required for this operation) + // workbook.Dispose(); // Not necessary as .NET GC will handle it + + return formattedDate; + } + } + + // Example usage + class Program + { + static void Main() + { + DateTime gregorianDate = new DateTime(2023, 5, 21); + string japaneseEra = JapaneseEraFormatter.GetJapaneseEraDateString(gregorianDate); + Console.WriteLine($"Gregorian: {gregorianDate:d} => Japanese Era: {japaneseEra}"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-subclass-of-globalizationsettings-overriding-getgrandtotalname-to-supply-a-culturespecific-grand-total-label.cs b/globalization-and-localization/create-a-subclass-of-globalizationsettings-overriding-getgrandtotalname-to-supply-a-culturespecific-grand-total-label.cs new file mode 100644 index 0000000000..35d5188012 --- /dev/null +++ b/globalization-and-localization/create-a-subclass-of-globalizationsettings-overriding-getgrandtotalname-to-supply-a-culturespecific-grand-total-label.cs @@ -0,0 +1,80 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsExamples +{ + // Custom globalization settings that returns a culture‑specific grand total label + public class CustomGlobalizationSettings : GlobalizationSettings + { + // Override the method that provides the grand total name for a given consolidation function + public override string GetGrandTotalName(ConsolidationFunction functionType) + { + // Example: use different labels for Sum and other functions based on current culture + // (In a real scenario you could look up resources per culture.) + if (functionType == ConsolidationFunction.Sum) + { + // English label + return "Grand Total (Sum)"; + } + else if (functionType == ConsolidationFunction.Average) + { + // French label + return "Total Général (Moyenne)"; + } + else + { + // Fallback to the base implementation for all other functions + return base.GetGrandTotalName(functionType); + } + } + } + + public class GlobalizationSettingsDemo + { + public static void Run() + { + // Create a new workbook (lifecycle rule: create) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a pivot table + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["B1"].PutValue("Amount"); + sheet.Cells["A2"].PutValue("Food"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["A3"].PutValue("Food"); + sheet.Cells["B3"].PutValue(80); + sheet.Cells["A4"].PutValue("Drink"); + sheet.Cells["B4"].PutValue(150); + sheet.Cells["A5"].PutValue("Drink"); + sheet.Cells["B5"].PutValue(200); + + // Apply the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Create a pivot table to demonstrate the custom grand total label + int pivotIndex = sheet.PivotTables.Add("A1:B5", "D1", "SalesPivot"); + PivotTable pivot = sheet.PivotTables[pivotIndex]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Category + int dataFieldIdx = pivot.AddFieldToArea(PivotFieldType.Data, 1); // Amount + pivot.DataFields[dataFieldIdx].Function = ConsolidationFunction.Sum; + + // Refresh and calculate the pivot table so that labels are generated + pivot.RefreshData(); + pivot.CalculateData(); + + // Save the workbook (lifecycle rule: save) + workbook.Save("CustomGrandTotalDemo.xlsx"); + } + } + + // Entry point for demonstration + class Program + { + static void Main() + { + GlobalizationSettingsDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-subclass-of-globalizationsettings-that-overrides-gettotalname-to-provide-a-localized-subtotal-label.cs b/globalization-and-localization/create-a-subclass-of-globalizationsettings-that-overrides-gettotalname-to-provide-a-localized-subtotal-label.cs new file mode 100644 index 0000000000..944f68138a --- /dev/null +++ b/globalization-and-localization/create-a-subclass-of-globalizationsettings-that-overrides-gettotalname-to-provide-a-localized-subtotal-label.cs @@ -0,0 +1,65 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsCustomGlobalization +{ + // Subclass of GlobalizationSettings that provides localized total names. + public class CustomGlobalizationSettings : GlobalizationSettings + { + // Override GetTotalName to return custom labels based on the consolidation function. + public override string GetTotalName(ConsolidationFunction functionType) + { + return functionType switch + { + ConsolidationFunction.Sum => "Localized Sum", + ConsolidationFunction.Average => "Localized Average", + ConsolidationFunction.Count => "Localized Count", + ConsolidationFunction.Max => "Localized Max", + ConsolidationFunction.Min => "Localized Min", + _ => base.GetTotalName(functionType) + }; + } + } + + class Program + { + static void Main() + { + // Create a new workbook. + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate sample data for a pivot table. + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Value"); + cells["A2"].PutValue("A"); + cells["B2"].PutValue(10); + cells["A3"].PutValue("B"); + cells["B3"].PutValue(20); + cells["A4"].PutValue("A"); + cells["B4"].PutValue(30); + cells["A5"].PutValue("B"); + cells["B5"].PutValue(40); + + // Apply the custom globalization settings to the workbook. + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Create a pivot table to demonstrate the custom total names. + int pivotIndex = sheet.PivotTables.Add("A1:B5", "D1", "SamplePivot"); + PivotTable pivot = sheet.PivotTables[pivotIndex]; + pivot.AddFieldToArea(PivotFieldType.Row, 0); // Category + int dataFieldIdx = pivot.AddFieldToArea(PivotFieldType.Data, 1); // Value + // Set the function to Sum; the overridden GetTotalName will be used for the total label. + pivot.DataFields[dataFieldIdx].Function = ConsolidationFunction.Sum; + + // Refresh and calculate the pivot table. + pivot.RefreshData(); + pivot.CalculateData(); + + // Save the workbook. + workbook.Save("CustomGlobalizationSettingsDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-test-suite-that-loads-workbooks-with-various-cultureinfo-values-and-verifies-date-parsing-accuracy.cs b/globalization-and-localization/create-a-test-suite-that-loads-workbooks-with-various-cultureinfo-values-and-verifies-date-parsing-accuracy.cs new file mode 100644 index 0000000000..939b92c2c9 --- /dev/null +++ b/globalization-and-localization/create-a-test-suite-that-loads-workbooks-with-various-cultureinfo-values-and-verifies-date-parsing-accuracy.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsCultureInfoTest +{ + class Program + { + static void Main() + { + // Path for the temporary workbook + const string workbookPath = "DateSample.xlsx"; + + // 1. Create a workbook with a known date value and save it + CreateSampleWorkbook(workbookPath); + + // 2. Define cultures to test + var cultures = new Dictionary + { + { "en-US", new CultureInfo("en-US") }, // MM/dd/yyyy + { "de-DE", new CultureInfo("de-DE") }, // dd.MM.yyyy + { "fr-FR", new CultureInfo("fr-FR") } // dd/MM/yyyy + }; + + // Expected date (January 15, 2023) + DateTime expectedDate = new DateTime(2023, 1, 15); + + // 3. Load the workbook with each culture and verify date parsing + foreach (var kvp in cultures) + { + string cultureName = kvp.Key; + CultureInfo culture = kvp.Value; + + // Use LoadOptions with the specific CultureInfo (rule: LoadOptions.CultureInfo) + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); + loadOptions.CultureInfo = culture; + + // Load the workbook (rule: load) + Workbook wb = new Workbook(workbookPath, loadOptions); + Worksheet sheet = wb.Worksheets[0]; + Cell dateCell = sheet.Cells["A1"]; + + // Retrieve the parsed date + DateTime parsedDate = dateCell.DateTimeValue; + + // Verify that the parsed date matches the expected date + if (parsedDate != expectedDate) + { + Console.WriteLine($"[FAIL] Culture {cultureName}: Parsed date {parsedDate:d} does not match expected {expectedDate:d}"); + } + else + { + Console.WriteLine($"[PASS] Culture {cultureName}: Parsed date correctly as {parsedDate:d}"); + } + } + + // Clean up (optional) + // System.IO.File.Delete(workbookPath); + } + + // Helper method to create a workbook containing a date in cell A1 and save it + static void CreateSampleWorkbook(string path) + { + // Create a new workbook (rule: create) + Workbook wb = new Workbook(); + + // Access the first worksheet + Worksheet sheet = wb.Worksheets[0]; + + // Put a known date value into cell A1 + DateTime sampleDate = new DateTime(2023, 1, 15); + sheet.Cells["A1"].PutValue(sampleDate); + + // Apply a date format (optional, does not affect parsing) + Style style = sheet.Cells["A1"].GetStyle(); + style.Custom = "mm/dd/yyyy"; + sheet.Cells["A1"].SetStyle(style); + + // Save the workbook (rule: save) + wb.Save(path, SaveFormat.Xlsx); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-a-utility-that-converts-date-columns-in-multiple-xls-files-to-japanese-era-format-and-outputs-pdfs.cs b/globalization-and-localization/create-a-utility-that-converts-date-columns-in-multiple-xls-files-to-japanese-era-format-and-outputs-pdfs.cs new file mode 100644 index 0000000000..13e3a13453 --- /dev/null +++ b/globalization-and-localization/create-a-utility-that-converts-date-columns-in-multiple-xls-files-to-japanese-era-format-and-outputs-pdfs.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace DateToJapaneseEraPdf +{ + class Program + { + static void Main(string[] args) + { + // Input folder containing XLS files + string inputFolder = @"C:\InputXls"; + // Output folder for generated PDFs + string outputFolder = @"C:\OutputPdf"; + + // Ensure input folder exists + if (!Directory.Exists(inputFolder)) + { + Console.WriteLine($"Input folder not found: {inputFolder}"); + return; + } + + // Ensure output folder exists + if (!Directory.Exists(outputFolder)) + Directory.CreateDirectory(outputFolder); + + // Custom Japanese era date format + const string japaneseEraFormat = "[$-ja-JP]ggge年M月d日"; + + // Process each .xls file in the input folder + foreach (string xlsPath in Directory.GetFiles(inputFolder, "*.xls")) + { + try + { + // Verify the file exists before loading + if (!File.Exists(xlsPath)) + { + Console.WriteLine($"File not found: {xlsPath}"); + continue; + } + + // Load the workbook + Workbook workbook = new Workbook(xlsPath); + + // Set regional settings to Japan (helps with era calculations) + workbook.Settings.Region = CountryCode.Japan; + + // Prepare a reusable style with the Japanese era format + Style eraStyle = workbook.CreateStyle(); + eraStyle.Custom = japaneseEraFormat; + + // Iterate through all worksheets and cells + foreach (Worksheet sheet in workbook.Worksheets) + { + Cells cells = sheet.Cells; + int maxRow = cells.MaxDataRow; + int maxCol = cells.MaxDataColumn; + + for (int row = 0; row <= maxRow; row++) + { + for (int col = 0; col <= maxCol; col++) + { + Cell cell = cells[row, col]; + // Apply style to DateTime cells + if (cell.Type == CellValueType.IsDateTime) + cell.SetStyle(eraStyle); + } + } + } + + // Determine the PDF output path + string pdfPath = Path.Combine(outputFolder, + Path.GetFileNameWithoutExtension(xlsPath) + ".pdf"); + + // Save directly to PDF + workbook.Save(pdfPath, SaveFormat.Pdf); + + Console.WriteLine($"Converted '{xlsPath}' to PDF at '{pdfPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"Error processing '{xlsPath}': {ex.Message}"); + } + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/create-an-application-that-loads-a-workbook-with-italian-cultureinfo-adds-subtotals-and-saves-the-result-as-pdf.cs b/globalization-and-localization/create-an-application-that-loads-a-workbook-with-italian-cultureinfo-adds-subtotals-and-saves-the-result-as-pdf.cs new file mode 100644 index 0000000000..c8b275651e --- /dev/null +++ b/globalization-and-localization/create-an-application-that-loads-a-workbook-with-italian-cultureinfo-adds-subtotals-and-saves-the-result-as-pdf.cs @@ -0,0 +1,50 @@ +using System; +using System.Globalization; +using System.IO; +using Aspose.Cells; + +class SubtotalPdfDemo +{ + static void Main() + { + try + { + // Path to the existing Excel file + string inputPath = "input.xlsx"; + + // Verify that the input file exists + if (!File.Exists(inputPath)) + { + Console.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the workbook with Italian culture settings + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx) + { + CultureInfo = new CultureInfo("it-IT") + }; + Workbook workbook = new Workbook(inputPath, loadOptions); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Define the data range (A1:C6) + CellArea dataArea = CellArea.CreateCellArea(0, 0, 5, 2); // rows 0-5, columns 0-2 + + // Add subtotal: group by first column, sum third column + cells.Subtotal(dataArea, 0, ConsolidationFunction.Sum, new int[] { 2 }); + + // Save the result as PDF + string outputPdf = "output.pdf"; + workbook.Save(outputPdf, SaveFormat.Pdf); + + Console.WriteLine("Workbook loaded with Italian culture, subtotal added, and saved as PDF."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/demonstrate-preserving-the-original-thread-culture-while-loading-a-workbook-with-french-cultureinfo-using-loadoptions.cs b/globalization-and-localization/demonstrate-preserving-the-original-thread-culture-while-loading-a-workbook-with-french-cultureinfo-using-loadoptions.cs new file mode 100644 index 0000000000..c5c507adb3 --- /dev/null +++ b/globalization-and-localization/demonstrate-preserving-the-original-thread-culture-while-loading-a-workbook-with-french-cultureinfo-using-loadoptions.cs @@ -0,0 +1,39 @@ +using System; +using System.Globalization; +using System.Threading; +using Aspose.Cells; + +class PreserveThreadCultureDemo +{ + static void Main() + { + // Store the original thread culture (e.g., en-US) + CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; + + // Create a sample workbook with a numeric value + Workbook sample = new Workbook(); + sample.Worksheets[0].Cells["A1"].PutValue(1234.56); + // Save the sample workbook to a file + sample.Save("sample.xlsx"); + + // Ensure the current thread culture is still the original one + Console.WriteLine("Thread culture before loading: " + Thread.CurrentThread.CurrentCulture.Name); + + // Create LoadOptions and set its CultureInfo to French (fr-FR) + LoadOptions loadOptions = new LoadOptions(); + loadOptions.CultureInfo = new CultureInfo("fr-FR"); // French uses comma as decimal separator + + // Load the workbook using the specified LoadOptions + Workbook loaded = new Workbook("sample.xlsx", loadOptions); + + // Retrieve the value of cell A1 as a string; it will be formatted according to French culture + string frenchFormattedValue = loaded.Worksheets[0].Cells["A1"].StringValue; + Console.WriteLine("Value formatted with French culture: " + frenchFormattedValue); + + // Verify that the thread culture has not changed after loading + Console.WriteLine("Thread culture after loading: " + Thread.CurrentThread.CurrentCulture.Name); + + // Restore the original culture (good practice if it was changed elsewhere) + Thread.CurrentThread.CurrentCulture = originalCulture; + } +} \ No newline at end of file diff --git a/globalization-and-localization/design-a-workflow-that-loads-a-workbook-with-arabic-cultureinfo-adds-righttoleft-subtotals-and-saves-as-pdf.cs b/globalization-and-localization/design-a-workflow-that-loads-a-workbook-with-arabic-cultureinfo-adds-righttoleft-subtotals-and-saves-as-pdf.cs new file mode 100644 index 0000000000..130c41990d --- /dev/null +++ b/globalization-and-localization/design-a-workflow-that-loads-a-workbook-with-arabic-cultureinfo-adds-righttoleft-subtotals-and-saves-as-pdf.cs @@ -0,0 +1,57 @@ +using System; +using System.Globalization; +using Aspose.Cells; +using Aspose.Cells.Saving; + +class Program +{ + static void Main() + { + // Set the current thread to Arabic culture (e.g., Saudi Arabia) + CultureInfo arabicCulture = new CultureInfo("ar-SA"); + System.Threading.Thread.CurrentThread.CurrentCulture = arabicCulture; + System.Threading.Thread.CurrentThread.CurrentUICulture = arabicCulture; + + // Load the existing workbook (replace with your actual file path) + string inputFile = "input.xlsx"; + Workbook workbook = new Workbook(inputFile); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + + // Enable right‑to‑left display for the worksheet + worksheet.DisplayRightToLeft = true; + + // Determine the data range (assumes data starts at A1 and occupies the used area) + int startRow = 0; + int startColumn = 0; + int endRow = worksheet.Cells.MaxDataRow; + int endColumn = worksheet.Cells.MaxDataColumn; + CellArea dataArea = CellArea.CreateCellArea(startRow, startColumn, endRow, endColumn); + + // Add subtotals: + // - Group by the first column (index 0) + // - Use SUM function on the second column (index 1) + // - Replace existing subtotals, no page breaks, summary below data + worksheet.Cells.Subtotal( + dataArea, + 0, // groupBy column index + ConsolidationFunction.Sum, // subtotal function + new int[] { 1 }, // columns to subtotal + true, // replace existing subtotals + false, // no page breaks between groups + true // place summary below data + ); + + // Configure PDF save options (set a font that supports Arabic characters) + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + DefaultFont = "Arial", // fallback font for Arabic text + CheckWorkbookDefaultFont = true // ensure default font is checked + }; + + // Save the workbook as PDF + string outputFile = "output.pdf"; + workbook.Save(outputFile, pdfOptions); + } +} \ No newline at end of file diff --git a/globalization-and-localization/develop-a-chartglobalizationsettings-derivative-that-overrides-getothername-for-a-localized-piechart-other-label.cs b/globalization-and-localization/develop-a-chartglobalizationsettings-derivative-that-overrides-getothername-for-a-localized-piechart-other-label.cs new file mode 100644 index 0000000000..f727eeb6d5 --- /dev/null +++ b/globalization-and-localization/develop-a-chartglobalizationsettings-derivative-that-overrides-getothername-for-a-localized-piechart-other-label.cs @@ -0,0 +1,48 @@ +using Aspose.Cells; +using Aspose.Cells.Charts; + +// Custom globalization settings that localizes the "Other" label +class CustomChartGlobalizationSettings : ChartGlobalizationSettings +{ + // Override to provide a localized name for the "Other" slice in pie charts + public override string GetOtherName() + { + return "Otros"; // Example: Spanish localization + } +} + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for a pie chart + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["A4"].PutValue("C"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(30); + worksheet.Cells["B3"].PutValue(50); + worksheet.Cells["B4"].PutValue(20); + + // Add a pie chart to the worksheet + int chartIndex = worksheet.Charts.Add(ChartType.Pie, 5, 0, 15, 5); + Chart chart = worksheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); // Values + chart.NSeries.CategoryData = "A2:A4"; // Categories + + // Apply the custom globalization settings to the workbook + GlobalizationSettings globalization = new GlobalizationSettings + { + ChartSettings = new CustomChartGlobalizationSettings() + }; + workbook.Settings.GlobalizationSettings = globalization; + + // Save the workbook (the chart will use the localized "Other" label) + workbook.Save("CustomOtherLabelPieChart.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/develop-a-console-application-that-prompts-users-to-select-a-target-language-and-applies-localization-to-a-workbook.cs b/globalization-and-localization/develop-a-console-application-that-prompts-users-to-select-a-target-language-and-applies-localization-to-a-workbook.cs new file mode 100644 index 0000000000..66cf2bff3f --- /dev/null +++ b/globalization-and-localization/develop-a-console-application-that-prompts-users-to-select-a-target-language-and-applies-localization-to-a-workbook.cs @@ -0,0 +1,51 @@ +using System; +using Aspose.Cells; +using Aspose.Cells; // Ensure Aspose.Cells library is referenced + +namespace WorkbookLocalizationDemo +{ + class Program + { + static void Main() + { + // Display available languages (CountryCode enum values) + Console.WriteLine("Select a target language for the workbook:"); + var values = Enum.GetValues(typeof(CountryCode)); + int index = 1; + foreach (CountryCode code in values) + { + Console.WriteLine($"{index}. {code}"); + index++; + } + + // Read user selection + Console.Write("Enter the number corresponding to your choice: "); + string input = Console.ReadLine(); + if (!int.TryParse(input, out int choice) || choice < 1 || choice > values.Length) + { + Console.WriteLine("Invalid selection. Exiting."); + return; + } + + // Map selection to CountryCode + CountryCode selectedCode = (CountryCode)values.GetValue(choice - 1); + Console.WriteLine($"You selected: {selectedCode}"); + + // Create a new workbook and add sample data + Workbook workbook = new Workbook(); // create workbook + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample Data"); + sheet.Cells["A2"].PutValue(123); + sheet.Cells["A3"].PutValue(DateTime.Now); + + // Apply localization using WorkbookSettings.LanguageCode property + workbook.Settings.LanguageCode = selectedCode; + + // Save the workbook + string fileName = "LocalizedWorkbook.xlsx"; + workbook.Save(fileName); // save workbook + + Console.WriteLine($"Workbook saved as '{fileName}' with language code set to {selectedCode}."); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/ensure-that-cell-comments-retain-their-original-language-while-function-names-are-localized-according-to-settings.cs b/globalization-and-localization/ensure-that-cell-comments-retain-their-original-language-while-function-names-are-localized-according-to-settings.cs new file mode 100644 index 0000000000..529076b4f3 --- /dev/null +++ b/globalization-and-localization/ensure-that-cell-comments-retain-their-original-language-while-function-names-are-localized-according-to-settings.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + // Custom globalization settings that only localize function names + public class CustomGlobalizationSettings : SettableGlobalizationSettings + { + // No additional overrides needed for comment titles + } + + public class CommentAndFunctionLocalizationDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Prepare sample data for the formula + worksheet.Cells["A1"].PutValue(10); + worksheet.Cells["A2"].PutValue(20); + worksheet.Cells["A3"].PutValue(30); + + // Create custom globalization settings + CustomGlobalizationSettings settings = new CustomGlobalizationSettings(); + + // Map the standard SUM function to its Spanish equivalent "SUMA" + settings.SetLocalFunctionName("SUM", "SUMA", true); + + // Apply the settings to the workbook + workbook.Settings.GlobalizationSettings = settings; + + // Add a comment in cell B2 with Spanish content + int commentIndex = worksheet.Comments.Add("B2"); + Comment comment = worksheet.Comments[commentIndex]; + comment.Note = "Este es un comentario en español."; + comment.IsVisible = true; + + // Set the comment author (title) directly + comment.Author = "Comentario de Celda"; + + // Use the localized function name in a formula + worksheet.Cells["B2"].Formula = "=SUMA(A1:A3)"; + + // Calculate formulas + workbook.CalculateFormula(); + + // Output results to console + Console.WriteLine($"Formula result in B2: {worksheet.Cells["B2"].Value}"); + Console.WriteLine($"Comment author (title): {comment.Author}"); + Console.WriteLine($"Comment note: {comment.Note}"); + + // Save the workbook + string outputPath = "CommentAndFunctionLocalizationDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point for demonstration + class Program + { + static void Main() + { + CommentAndFunctionLocalizationDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/ensure-that-pivot-tables-reflect-localized-subtotal-labels-when-the-workbook-is-opened-in-the-target-language.cs b/globalization-and-localization/ensure-that-pivot-tables-reflect-localized-subtotal-labels-when-the-workbook-is-opened-in-the-target-language.cs new file mode 100644 index 0000000000..6594acaa7e --- /dev/null +++ b/globalization-and-localization/ensure-that-pivot-tables-reflect-localized-subtotal-labels-when-the-workbook-is-opened-in-the-target-language.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Settings; + +namespace AsposeCellsExamples +{ + public class LocalizedPivotSubtotalsDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + + // Populate sample data for the pivot table + dataSheet.Cells["A1"].PutValue("Category"); + dataSheet.Cells["B1"].PutValue("Amount"); + dataSheet.Cells["A2"].PutValue("Food"); + dataSheet.Cells["B2"].PutValue(120); + dataSheet.Cells["A3"].PutValue("Food"); + dataSheet.Cells["B3"].PutValue(80); + dataSheet.Cells["A4"].PutValue("Drink"); + dataSheet.Cells["B4"].PutValue(150); + dataSheet.Cells["A5"].PutValue("Drink"); + dataSheet.Cells["B5"].PutValue(70); + + // Add a pivot table based on the data range + int pivotIndex = dataSheet.PivotTables.Add("A1:B5", "D1", "SalesPivot"); + PivotTable pivotTable = dataSheet.PivotTables[pivotIndex]; + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); // Category as row field + pivotTable.AddFieldToArea(PivotFieldType.Data, 1); // Amount as data field + + // Customize subtotal texts + SettablePivotGlobalizationSettings pivotSettings = new SettablePivotGlobalizationSettings(); + pivotSettings.SetTextOfSubTotal(PivotFieldSubtotalType.Sum, "Σ Total"); + pivotSettings.SetTextOfSubTotal(PivotFieldSubtotalType.Count, "Count Total"); + pivotSettings.SetTextOfSubTotal(PivotFieldSubtotalType.Average, "Avg Total"); + pivotSettings.SetTextOfSubTotal(PivotFieldSubtotalType.Max, "Maximum"); + pivotSettings.SetTextOfSubTotal(PivotFieldSubtotalType.Min, "Minimum"); + + // Apply settings to workbook + workbook.Settings.GlobalizationSettings.PivotSettings = pivotSettings; + + // Refresh and calculate pivot table + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + // Save workbook + string outputPath = "LocalizedPivotSubtotals.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + + // Entry point + public static void Main(string[] args) + { + Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/generate-a-report-listing-all-cells-converted-to-japanese-dates-including-original-gregorian-values-for-reference.cs b/globalization-and-localization/generate-a-report-listing-all-cells-converted-to-japanese-dates-including-original-gregorian-values-for-reference.cs new file mode 100644 index 0000000000..c0606a9bc9 --- /dev/null +++ b/globalization-and-localization/generate-a-report-listing-all-cells-converted-to-japanese-dates-including-original-gregorian-values-for-reference.cs @@ -0,0 +1,73 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Settings; + +class JapaneseDateReport +{ + static void Main() + { + // Create a new workbook (source data) + Workbook wb = new Workbook(); + Worksheet ws = wb.Worksheets[0]; + + // Sample Gregorian dates (replace with real data or load from file) + ws.Cells["A1"].PutValue(new DateTime(2023, 1, 15)); + ws.Cells["A2"].PutValue(new DateTime(2023, 2, 20)); + ws.Cells["B1"].PutValue("Not a date"); + ws.Cells["B2"].PutValue(123); + + // Set regional settings to Japan (affects date handling) + wb.Settings.Region = CountryCode.Japan; + + // Add a worksheet to hold the report + int reportIndex = wb.Worksheets.Add(); + Worksheet report = wb.Worksheets[reportIndex]; + report.Name = "JapaneseDateReport"; + + // Write header row + report.Cells[0, 0].PutValue("Cell Address"); + report.Cells[0, 1].PutValue("Gregorian Value"); + report.Cells[0, 2].PutValue("Japanese Date"); + + int reportRow = 1; + + // Scan all used cells in the source worksheet + int maxRow = ws.Cells.MaxDataRow; + int maxCol = ws.Cells.MaxDataColumn; + + for (int r = 0; r <= maxRow; r++) + { + for (int c = 0; c <= maxCol; c++) + { + Cell cell = ws.Cells[r, c]; + + // Identify cells that contain a DateTime value + if (cell.Type == CellValueType.IsDateTime) + { + // Original cell address (e.g., "A1") + string address = cell.Name; + + // Original Gregorian date + DateTime gregorian = cell.DateTimeValue; + + // Write address and Gregorian value to the report + report.Cells[reportRow, 0].PutValue(address); + report.Cells[reportRow, 1].PutValue(gregorian.ToString("yyyy-MM-dd")); + + // Write the same date with Japanese formatting + Cell japCell = report.Cells[reportRow, 2]; + japCell.PutValue(gregorian); + Style style = japCell.GetStyle(); + // Japanese date format (e.g., "2023年1月15日") + style.Custom = "[$-ja-JP]yyyy年m月d日"; + japCell.SetStyle(style); + + reportRow++; + } + } + } + + // Save the workbook containing the report + wb.Save("JapaneseDateReport.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/generate-a-report-listing-processed-workbooks-applied-locales-and-any-localization-errors-encountered.cs b/globalization-and-localization/generate-a-report-listing-processed-workbooks-applied-locales-and-any-localization-errors-encountered.cs new file mode 100644 index 0000000000..9b2548016d --- /dev/null +++ b/globalization-and-localization/generate-a-report-listing-processed-workbooks-applied-locales-and-any-localization-errors-encountered.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; + +namespace WorkbookLocalizationReport +{ + // Custom globalization settings that can be extended for different locales + class CustomGlobalizationSettings : GlobalizationSettings + { + private readonly string _locale; + + public CustomGlobalizationSettings(string locale) + { + _locale = locale; + } + + // Example: localize boolean values (can be expanded per locale) + public override string GetBooleanValueString(bool bv) + { + return _locale switch + { + "zh" => bv ? "真" : "假", + "ru" => bv ? "ИСТИНА" : "ЛОЖЬ", + _ => base.GetBooleanValueString(bv) + }; + } + + // Example: localize error strings (can be expanded per locale) + public override string GetErrorValueString(string err) + { + return _locale switch + { + "zh" => err switch + { + "#NAME?" => "#名称?", + "#DIV/0!" => "#除以0!", + "#REF!" => "#引用!", + "#VALUE!" => "#值!", + "#N/A" => "#无效!", + "#NUM!" => "#数值!", + "#NULL!" => "#空!", + _ => err + }, + "ru" => err switch + { + "#NAME?" => "#ИМЯ?", + "#DIV/0!" => "#ДЕЛ/0!", + "#REF!" => "#ССЫЛКА!", + "#VALUE!" => "#ЗНАЧ?", + "#N/A" => "#Н/Д", + "#NUM!" => "#ЧИСЛО!", + "#NULL!" => "#ПУСТО!", + _ => err + }, + _ => base.GetErrorValueString(err) + }; + } + } + + class Program + { + static void Main() + { + // List of workbooks to process (full paths) + var workbookPaths = new List + { + @"C:\Data\Report_en.xlsx", + @"C:\Data\Report_zh.xlsx", + @"C:\Data\Report_ru.xlsx" + }; + + // Mapping of workbook path to locale identifier + var workbookLocales = new Dictionary + { + { @"C:\Data\Report_en.xlsx", "en" }, + { @"C:\Data\Report_zh.xlsx", "zh" }, + { @"C:\Data\Report_ru.xlsx", "ru" } + }; + + // Store report entries + var reportLines = new List(); + reportLines.Add("Processed Workbooks Report"); + reportLines.Add("=========================="); + reportLines.Add(""); + + foreach (var path in workbookPaths) + { + // Verify file exists + if (!File.Exists(path)) + { + reportLines.Add($"File not found: {path}"); + continue; + } + + // Load workbook (lifecycle rule: use constructor with path) + var workbook = new Workbook(path); + + // Determine locale for this workbook + workbookLocales.TryGetValue(path, out string locale); + locale ??= "en"; + + // Apply custom globalization settings (lifecycle rule: set property) + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(locale); + + // Collect localization errors + var errors = new List(); + + // Iterate through all worksheets and cells + foreach (Worksheet sheet in workbook.Worksheets) + { + Cells cells = sheet.Cells; + // Define the used range to avoid scanning empty 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]; + // Check if the cell contains an error value + if (cell.Type == CellValueType.IsError) + { + // Retrieve the original error string + string originalError = cell.StringValue; + // Get the localized representation via globalization settings + string localizedError = workbook.Settings.GlobalizationSettings.GetErrorValueString(originalError); + errors.Add($"Sheet '{sheet.Name}'!{cell.Name}: {originalError} => {localizedError}"); + } + } + } + } + + // Add entry to report + reportLines.Add($"Workbook: {Path.GetFileName(path)}"); + reportLines.Add($"Locale applied: {locale}"); + if (errors.Count == 0) + { + reportLines.Add("No localization errors detected."); + } + else + { + reportLines.Add("Localization errors:"); + foreach (var err in errors) + { + reportLines.Add(" - " + err); + } + } + reportLines.Add(""); + + // (Optional) Save the workbook after applying globalization settings + // Using lifecycle rule: Save method + string outputPath = Path.Combine(Path.GetDirectoryName(path) ?? "", $"Processed_{Path.GetFileName(path)}"); + workbook.Save(outputPath); + } + + // Output the report to console + foreach (var line in reportLines) + { + Console.WriteLine(line); + } + + // Also write the report to a text file + string reportFile = @"C:\Data\WorkbookLocalizationReport.txt"; + File.WriteAllLines(reportFile, reportLines); + Console.WriteLine($"Report saved to: {reportFile}"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-a-fallback-mechanism-that-reverts-to-default-globalization-settings-if-custom-label-methods-throw-exceptions.cs b/globalization-and-localization/implement-a-fallback-mechanism-that-reverts-to-default-globalization-settings-if-custom-label-methods-throw-exceptions.cs new file mode 100644 index 0000000000..9dfe5748f5 --- /dev/null +++ b/globalization-and-localization/implement-a-fallback-mechanism-that-reverts-to-default-globalization-settings-if-custom-label-methods-throw-exceptions.cs @@ -0,0 +1,60 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsFallbackDemo +{ + // Custom globalization settings that intentionally throws an exception + // for demonstration purposes. + public class CustomGlobalizationSettings : GlobalizationSettings + { + public override string GetAllName() + { + // Simulate a failure in custom label method. + throw new InvalidOperationException("Custom GetAllName failed."); + } + + // You can override other label methods similarly if needed. + } + + class Program + { + static void Main() + { + // Create a new workbook. + Workbook workbook = new Workbook(); + + // Assign the custom globalization settings. + workbook.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + + // Attempt to retrieve a custom label. + string allLabel; + try + { + // This call will invoke the overridden method which throws. + allLabel = workbook.Settings.GlobalizationSettings.GetAllName(); + Console.WriteLine($"Custom '(All)' label: {allLabel}"); + } + catch (Exception ex) + { + Console.WriteLine($"Custom label method threw an exception: {ex.Message}"); + Console.WriteLine("Reverting to default globalization settings."); + + // Revert to the default globalization settings. + workbook.Settings.GlobalizationSettings = new GlobalizationSettings(); + + // Retry using the default implementation. + allLabel = workbook.Settings.GlobalizationSettings.GetAllName(); + Console.WriteLine($"Default '(All)' label after fallback: {allLabel}"); + } + + // Demonstrate that the workbook can still be used normally. + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue("Sample Data"); + sheet.Cells["A2"].PutValue(123); + sheet.Cells["B1"].Formula = $"={allLabel}(A2)"; // Example usage; may not be a valid formula. + + // Save the workbook. + workbook.Save("FallbackDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-a-feature-that-automatically-selects-the-appropriate-japanese-era-based-on-year-when-converting-dates-in-bulk.cs b/globalization-and-localization/implement-a-feature-that-automatically-selects-the-appropriate-japanese-era-based-on-year-when-converting-dates-in-bulk.cs new file mode 100644 index 0000000000..fa5bf42d30 --- /dev/null +++ b/globalization-and-localization/implement-a-feature-that-automatically-selects-the-appropriate-japanese-era-based-on-year-when-converting-dates-in-bulk.cs @@ -0,0 +1,72 @@ +using System; +using System.Globalization; +using Aspose.Cells; +using Aspose.Cells.Settings; + +namespace AsposeCellsJapaneseEraDemo +{ + class Program + { + static void Main() + { + // Create a new workbook instance (load existing file) + Workbook workbook = new Workbook("InputData.xlsx"); + + // Set workbook region to Japan to ensure Japanese calendar handling + workbook.Settings.Region = CountryCode.Japan; + + // Get the first worksheet (or iterate all worksheets as needed) + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Define Japanese eras with start year (Gregorian) and era name + var eras = new (int startYear, string name)[] + { + (1868, "Meiji"), + (1912, "Taisho"), + (1926, "Showa"), + (1989, "Heisei"), + (2019, "Reiwa") + }; + + // Iterate through all used cells + foreach (Cell cell in cells) + { + // Process only cells that contain a DateTime value + if (cell.Type == CellValueType.IsDateTime) + { + DateTime dt = cell.DateTimeValue; + string eraName = ""; + int eraYear = 0; + + // Find the appropriate era based on the Gregorian year + for (int i = eras.Length - 1; i >= 0; i--) + { + if (dt.Year >= eras[i].startYear) + { + eraName = eras[i].name; + eraYear = dt.Year - eras[i].startYear + 1; // Japanese era year starts at 1 + break; + } + } + + // Fallback if no era matched (should not happen for modern dates) + if (string.IsNullOrEmpty(eraName)) + { + eraName = "Unknown"; + eraYear = dt.Year; + } + + // Build formatted string: e.g., "Reiwa 3年5月21日" + string formatted = $"{eraName} {eraYear}年{dt.Month}月{dt.Day}日"; + + // Replace the cell value with the formatted string + cell.PutValue(formatted); + } + } + + // Save the modified workbook + workbook.Save("OutputWithJapaneseEra.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-a-feature-that-switches-localization-at-runtime-based-on-user-selection-without-reloading-the-workbook.cs b/globalization-and-localization/implement-a-feature-that-switches-localization-at-runtime-based-on-user-selection-without-reloading-the-workbook.cs new file mode 100644 index 0000000000..4110718a1e --- /dev/null +++ b/globalization-and-localization/implement-a-feature-that-switches-localization-at-runtime-based-on-user-selection-without-reloading-the-workbook.cs @@ -0,0 +1,103 @@ +using System; +using System.Globalization; +using System.IO; +using Aspose.Cells; + +namespace LocalizationDemo +{ + class LocalizationSwitcher + { + static void Main() + { + try + { + // Create a new workbook and add sample data + Workbook wb = new Workbook(); + Worksheet ws = wb.Worksheets[0]; + ws.Cells["A1"].PutValue(10); + ws.Cells["A2"].PutValue(20); + ws.Cells["A3"].Formula = "=SUM(A1:A2)"; + + // Calculate with the default (English) locale + wb.CalculateFormula(); + Console.WriteLine($"Result with default locale: {ws.Cells["A3"].Value}"); + + // Switch localization to French at runtime (no reload required) + SwitchLocalization(wb, CountryCode.France); + + // Re‑calculate to reflect any locale‑dependent changes + wb.CalculateFormula(); + Console.WriteLine($"Result after switching to French: {ws.Cells["A3"].Value}"); + + // Map the standard function name "SUM" to its French equivalent "SOMME" + SetLocalizedFunction(wb, "SUM", "SOMME"); + + // Use the localized function name in a new formula + ws.Cells["B1"].Formula = "=SOMME(A1:A2)"; + wb.CalculateFormula(); + Console.WriteLine($"Result using localized function name 'SOMME': {ws.Cells["B1"].Value}"); + + // Save the workbook (optional) + string outputPath = "LocalizationDemo.xlsx"; + wb.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + // Changes the workbook's UI language, region and culture info at runtime + static void SwitchLocalization(Workbook workbook, CountryCode country) + { + // Set UI language and regional settings + workbook.Settings.LanguageCode = country; + workbook.Settings.Region = country; + + // Determine appropriate culture name for the given CountryCode + string cultureName = GetCultureName(country); + if (!string.IsNullOrEmpty(cultureName)) + { + workbook.Settings.CultureInfo = new CultureInfo(cultureName); + } + + // Ensure globalization settings are replaceable + workbook.Settings.GlobalizationSettings = new SettableGlobalizationSettings(); + } + + // Returns a valid .NET culture name for a given CountryCode + static string GetCultureName(CountryCode country) + { + switch (country) + { + case CountryCode.France: + return "fr-FR"; + case CountryCode.Germany: + return "de-DE"; + case CountryCode.Spain: + return "es-ES"; + case CountryCode.UnitedKingdom: + return "en-GB"; + // Add more mappings as needed + default: + return CultureInfo.InvariantCulture.Name; + } + } + + // Adds a bidirectional mapping between a standard function name and a localized name + static void SetLocalizedFunction(Workbook workbook, string standardName, string localName) + { + // Ensure the workbook uses SettableGlobalizationSettings + var settings = workbook.Settings.GlobalizationSettings as SettableGlobalizationSettings; + if (settings == null) + { + settings = new SettableGlobalizationSettings(); + workbook.Settings.GlobalizationSettings = settings; + } + + // Map the standard function to the local name (bidirectional = true) + settings.SetLocalFunctionName(standardName, localName, true); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-a-method-that-switches-globalizationsettings-at-runtime-based-on-userselected-language-before-chart-creation.cs b/globalization-and-localization/implement-a-method-that-switches-globalizationsettings-at-runtime-based-on-userselected-language-before-chart-creation.cs new file mode 100644 index 0000000000..1fb72f35a1 --- /dev/null +++ b/globalization-and-localization/implement-a-method-that-switches-globalizationsettings-at-runtime-based-on-userselected-language-before-chart-creation.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; + +namespace AsposeCellsDemo +{ + public static class ChartGlobalizationHelper + { + public static void CreateChartWithLanguage(string languageCode, string outputPath) + { + try + { + // Ensure the output directory exists. + string dir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + // Create a new workbook and get the first worksheet. + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Prepare sample data for the chart. + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("Q1"); + sheet.Cells["A3"].PutValue("Q2"); + sheet.Cells["A4"].PutValue("Q3"); + sheet.Cells["B1"].PutValue("Series"); + sheet.Cells["B2"].PutValue(120); + sheet.Cells["B3"].PutValue(150); + sheet.Cells["B4"].PutValue(180); + + // Build language‑specific chart globalization settings. + SettableChartGlobalizationSettings chartSettings = GetChartSettingsForLanguage(languageCode); + + // Apply globalization settings to the workbook. + SettableGlobalizationSettings globalSettings = new SettableGlobalizationSettings + { + ChartSettings = chartSettings + }; + workbook.Settings.GlobalizationSettings = globalSettings; + + // Create a column chart. + int chartIndex = sheet.Charts.Add(ChartType.Column, 6, 0, 20, 10); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + + // Set localized chart title. + chart.Title.Text = chartSettings.GetChartTitleName(); + + // Save the workbook. + workbook.Save(outputPath); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error creating chart: {ex.Message}"); + throw; + } + } + + private static SettableChartGlobalizationSettings GetChartSettingsForLanguage(string languageCode) + { + var settings = new SettableChartGlobalizationSettings(); + + switch (languageCode?.ToLowerInvariant()) + { + case "en": + settings.SetChartTitleName("Sales Overview"); + settings.SetSeriesName("Sales Series"); + settings.SetLegendIncreaseName("Increase"); + settings.SetLegendDecreaseName("Decrease"); + settings.SetOtherName("Other"); + break; + case "fr": + settings.SetChartTitleName("Aperçu des ventes"); + settings.SetSeriesName("Série des ventes"); + settings.SetLegendIncreaseName("Augmentation"); + settings.SetLegendDecreaseName("Diminution"); + settings.SetOtherName("Autre"); + break; + case "de": + settings.SetChartTitleName("Verkaufsübersicht"); + settings.SetSeriesName("Verkaufsreihe"); + settings.SetLegendIncreaseName("Zunahme"); + settings.SetLegendDecreaseName("Abnahme"); + settings.SetOtherName("Andere"); + break; + case "es": + settings.SetChartTitleName("Resumen de ventas"); + settings.SetSeriesName("Serie de ventas"); + settings.SetLegendIncreaseName("Incremento"); + settings.SetLegendDecreaseName("Disminución"); + settings.SetOtherName("Otro"); + break; + default: + // Fallback to English. + settings.SetChartTitleName("Sales Overview"); + settings.SetSeriesName("Sales Series"); + settings.SetLegendIncreaseName("Increase"); + settings.SetLegendDecreaseName("Decrease"); + settings.SetOtherName("Other"); + break; + } + + return settings; + } + } + + public class Program + { + public static void Main(string[] args) + { + try + { + // Example usage: create a French chart. + string language = "fr"; + string outputFile = "Chart_French.xlsx"; + + ChartGlobalizationHelper.CreateChartWithLanguage(language, outputFile); + Console.WriteLine($"Workbook saved to {outputFile}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error in Main: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-a-method-to-reset-globalizationsettings-to-default-english-behavior-for-specific-worksheets.cs b/globalization-and-localization/implement-a-method-to-reset-globalizationsettings-to-default-english-behavior-for-specific-worksheets.cs new file mode 100644 index 0000000000..be6aefa683 --- /dev/null +++ b/globalization-and-localization/implement-a-method-to-reset-globalizationsettings-to-default-english-behavior-for-specific-worksheets.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public static class GlobalizationResetHelper + { + /// + /// Resets the workbook's globalization settings to the default English values. + /// + /// Workbook to modify. + /// Indices are ignored (kept for compatibility). + public static void ResetGlobalizationSettingsToDefaultEnglish(Workbook workbook, int[] worksheetIndices) + { + // Default English globalization settings + GlobalizationSettings defaultSettings = new GlobalizationSettings(); + workbook.Settings.GlobalizationSettings = defaultSettings; + } + + /// + /// Demonstrates resetting globalization settings. + /// + public static void Run() + { + try + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Add sample data + Worksheet ws1 = wb.Worksheets[0]; + ws1.Name = "Sheet1"; + ws1.Cells["A1"].PutValue(true); // Boolean value + ws1.Cells["A2"].PutValue("#DIV/0!"); // Error value + + // Apply custom Russian globalization + SettableGlobalizationSettings customSettings = new SettableGlobalizationSettings(); + customSettings.SetBooleanValueString(true, "ИСТИНА"); + customSettings.SetBooleanValueString(false, "ЛОЖЬ"); + wb.Settings.GlobalizationSettings = customSettings; + + // Show values before reset + Console.WriteLine("Before reset:"); + Console.WriteLine($"A1 (bool) => {ws1.Cells["A1"].StringValue}"); + Console.WriteLine($"A2 (error) => {ws1.Cells["A2"].StringValue}"); + + // Reset to default English (worksheetIndices not used) + ResetGlobalizationSettingsToDefaultEnglish(wb, new int[] { 0 }); + + // Show values after reset + Console.WriteLine("\nAfter reset:"); + Console.WriteLine($"A1 (bool) => {ws1.Cells["A1"].StringValue}"); + Console.WriteLine($"A2 (error) => {ws1.Cells["A2"].StringValue}"); + + // Save the workbook + string outputPath = "ResetGlobalizationDemo.xlsx"; + wb.Save(outputPath); + Console.WriteLine($"\nWorkbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Application entry point + public class Program + { + public static void Main(string[] args) + { + GlobalizationResetHelper.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-error-handling-for-loadoptionscultureinfo-when-an-unsupported-locale-identifier-is-supplied-during-workbook-loading.cs b/globalization-and-localization/implement-error-handling-for-loadoptionscultureinfo-when-an-unsupported-locale-identifier-is-supplied-during-workbook-loading.cs new file mode 100644 index 0000000000..83506755e8 --- /dev/null +++ b/globalization-and-localization/implement-error-handling-for-loadoptionscultureinfo-when-an-unsupported-locale-identifier-is-supplied-during-workbook-loading.cs @@ -0,0 +1,89 @@ +using System; +using System.Globalization; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class LoadOptionsCultureInfoErrorHandlingDemo + { + public static void Run() + { + try + { + // Path to a sample workbook (created if it does not exist) + string sourcePath = "sample.xlsx"; + EnsureSampleWorkbookExists(sourcePath); + + // Locale identifier that might be unsupported + string localeId = "xx-XX"; // intentionally invalid + + // Prepare LoadOptions with error handling for CultureInfo + LoadOptions loadOptions = new LoadOptions(); + + try + { + // Attempt to assign the requested CultureInfo + loadOptions.CultureInfo = new CultureInfo(localeId); + } + catch (CultureNotFoundException ex) + { + // Unsupported locale – log and fall back to InvariantCulture + Console.WriteLine($"Locale '{localeId}' is not supported: {ex.Message}"); + loadOptions.CultureInfo = CultureInfo.InvariantCulture; + Console.WriteLine("Falling back to InvariantCulture."); + } + + // Verify source file exists before loading + if (!File.Exists(sourcePath)) + { + Console.WriteLine($"Source file '{sourcePath}' not found."); + return; + } + + // Load the workbook using the prepared LoadOptions + Workbook workbook = new Workbook(sourcePath, loadOptions); + + // Demonstrate that the culture is applied (e.g., number formatting) + Worksheet sheet = workbook.Worksheets[0]; + Cell cell = sheet.Cells["A2"]; + cell.PutValue(1234.56); // value to be formatted + + // Apply a numeric style to show culture‑specific decimal separator + Style style = workbook.CreateStyle(); + style.Number = 2; // two decimal places + cell.SetStyle(style); + + // Save the workbook + string outputPath = "output.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + // Catch any unexpected exceptions + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + + // Helper to create a minimal workbook if the sample file is missing + private static void EnsureSampleWorkbookExists(string path) + { + if (!File.Exists(path)) + { + Workbook wb = new Workbook(); + wb.Worksheets[0].Cells["A1"].PutValue("Sample"); + wb.Save(path); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + LoadOptionsCultureInfoErrorHandlingDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-fallback-to-english-function-names-when-a-requested-locale-lacks-a-defined-mapping.cs b/globalization-and-localization/implement-fallback-to-english-function-names-when-a-requested-locale-lacks-a-defined-mapping.cs new file mode 100644 index 0000000000..28f20b75a2 --- /dev/null +++ b/globalization-and-localization/implement-fallback-to-english-function-names-when-a-requested-locale-lacks-a-defined-mapping.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + // Custom globalization settings that fall back to English (standard) function names + // when a locale‑specific mapping is not defined. + public class FallbackGlobalizationSettings : GlobalizationSettings + { + // Mapping from standard (English) function names to localized names. + private readonly Dictionary _standardToLocal = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "SUM", "LOCALSUM" } // Example mapping; add more as needed. + }; + + // Reverse lookup dictionary. + private readonly Dictionary _localToStandard; + + public FallbackGlobalizationSettings() + { + _localToStandard = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var kvp in _standardToLocal) + _localToStandard[kvp.Value] = kvp.Key; + } + + // Returns the localized function name if defined; otherwise falls back to the standard name. + public override string GetLocalFunctionName(string standardName) + { + if (standardName == null) throw new ArgumentNullException(nameof(standardName)); + + return _standardToLocal.TryGetValue(standardName, out string localName) ? localName : standardName; + } + + // Returns the standard function name for a given localized name. + // If the localized name is not mapped, assume it is already the standard English name. + public override string GetStandardFunctionName(string localName) + { + if (localName == null) throw new ArgumentNullException(nameof(localName)); + + return _localToStandard.TryGetValue(localName, out string standardName) ? standardName : localName; + } + } + + public class FallbackLocalizationDemo + { + public static void Run() + { + try + { + // Create a new workbook. + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Apply the custom globalization settings. + workbook.Settings.GlobalizationSettings = new FallbackGlobalizationSettings(); + + // Populate sample data. + sheet.Cells["B1"].PutValue(5); + sheet.Cells["B2"].PutValue(15); + + // Use the localized function name in a formula. + // NOTE: If the custom globalization mapping does not work in a particular environment, + // fall back to the standard function name to avoid runtime errors. + Cell localizedCell = sheet.Cells["B3"]; + localizedCell.Formula = "=LOCALSUM(B1:B2)"; + + // Use the standard English function name in another formula. + Cell standardCell = sheet.Cells["B4"]; + standardCell.Formula = "=SUM(B1:B2)"; + + // Calculate all formulas. + workbook.CalculateFormula(); + + // Output results. + Console.WriteLine($"Result using localized name (LOCALSUM): {localizedCell.DoubleValue}"); + Console.WriteLine($"Result using standard name (SUM): {standardCell.DoubleValue}"); + + // Save the workbook (optional). + string outputPath = "FallbackLocalizationDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to: {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Entry point. + class Program + { + static void Main() + { + FallbackLocalizationDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/implement-logging-to-capture-which-culturespecific-label-methods-are-called-during-chart-rendering-for-debugging.cs b/globalization-and-localization/implement-logging-to-capture-which-culturespecific-label-methods-are-called-during-chart-rendering-for-debugging.cs new file mode 100644 index 0000000000..48b8f45908 --- /dev/null +++ b/globalization-and-localization/implement-logging-to-capture-which-culturespecific-label-methods-are-called-during-chart-rendering-for-debugging.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections; +using Aspose.Cells; +using Aspose.Cells.Charts; + +class Program +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Populate sample data for the chart + worksheet.Cells["A1"].PutValue("Category"); + worksheet.Cells["A2"].PutValue("A"); + worksheet.Cells["A3"].PutValue("B"); + worksheet.Cells["A4"].PutValue("C"); + worksheet.Cells["B1"].PutValue("Value"); + worksheet.Cells["B2"].PutValue(10); + worksheet.Cells["B3"].PutValue(20); + worksheet.Cells["B4"].PutValue(30); + + // Add a column chart + int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 0, 15, 5); + Chart chart = worksheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B4", true); + chart.NSeries.CategoryData = "A2:A4"; + chart.Title.Text = "Sample Chart"; + + // Attach custom globalization settings that log each method call + workbook.Settings.GlobalizationSettings = new GlobalizationSettings + { + ChartSettings = new LoggingChartGlobalizationSettings() + }; + + // Force chart calculation so that labels are generated + chart.Calculate(); + + // Access legend labels to trigger label generation and observe logs + Console.WriteLine("Legend Labels:"); + foreach (string label in chart.Legend.GetLegendLabels()) + { + Console.WriteLine(label); + } + + // Save the workbook + workbook.Save("LoggingChartGlobalization.xlsx"); + } + + // Custom ChartGlobalizationSettings that logs when culture‑specific label methods are invoked + class LoggingChartGlobalizationSettings : ChartGlobalizationSettings + { + public override string GetLegendIncreaseName() + { + string result = base.GetLegendIncreaseName(); + Console.WriteLine("[Log] GetLegendIncreaseName called, returning: " + result); + return result; + } + + public override string GetLegendDecreaseName() + { + string result = base.GetLegendDecreaseName(); + Console.WriteLine("[Log] GetLegendDecreaseName called, returning: " + result); + return result; + } + + public override string GetLegendTotalName() + { + string result = base.GetLegendTotalName(); + Console.WriteLine("[Log] GetLegendTotalName called, returning: " + result); + return result; + } + + public override string GetOtherName() + { + string result = base.GetOtherName(); + Console.WriteLine("[Log] GetOtherName called, returning: " + result); + return result; + } + + public override string GetSeriesName() + { + string result = base.GetSeriesName(); + Console.WriteLine("[Log] GetSeriesName called, returning: " + result); + return result; + } + + public override string GetChartTitleName() + { + string result = base.GetChartTitleName(); + Console.WriteLine("[Log] GetChartTitleName called, returning: " + result); + return result; + } + + public override string GetAxisTitleName() + { + string result = base.GetAxisTitleName(); + Console.WriteLine("[Log] GetAxisTitleName called, returning: " + result); + return result; + } + + public override string GetAxisUnitName(DisplayUnitType type) + { + string result = base.GetAxisUnitName(type); + Console.WriteLine("[Log] GetAxisUnitName called for " + type + ", returning: " + result); + return result; + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/load-an-xlsx-workbook-using-loadoptions-with-cultureinfo-set-to-french-preserving-thread-culture.cs b/globalization-and-localization/load-an-xlsx-workbook-using-loadoptions-with-cultureinfo-set-to-french-preserving-thread-culture.cs new file mode 100644 index 0000000000..f179e62067 --- /dev/null +++ b/globalization-and-localization/load-an-xlsx-workbook-using-loadoptions-with-cultureinfo-set-to-french-preserving-thread-culture.cs @@ -0,0 +1,35 @@ +using System; +using System.Globalization; +using System.Threading; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Preserve the original thread culture + CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; + + try + { + // Set thread culture to French (France) to match the load options + Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); + + // Create LoadOptions and assign French culture + LoadOptions loadOptions = new LoadOptions(); + loadOptions.CultureInfo = new CultureInfo("fr-FR"); + + // Load the XLSX workbook using the specified LoadOptions + Workbook workbook = new Workbook("input.xlsx", loadOptions); + + // Example usage: read the string value of cell A1 + string cellValue = workbook.Worksheets[0].Cells["A1"].StringValue; + Console.WriteLine($"A1 value: {cellValue}"); + } + finally + { + // Restore the original thread culture + Thread.CurrentThread.CurrentCulture = originalCulture; + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/load-the-configuration-at-runtime-and-instantiate-the-appropriate-localization-class-based-on-user-input.cs b/globalization-and-localization/load-the-configuration-at-runtime-and-instantiate-the-appropriate-localization-class-based-on-user-input.cs new file mode 100644 index 0000000000..451334b855 --- /dev/null +++ b/globalization-and-localization/load-the-configuration-at-runtime-and-instantiate-the-appropriate-localization-class-based-on-user-input.cs @@ -0,0 +1,102 @@ +using System; +using System.Globalization; +using System.IO; +using Aspose.Cells; + +class Program +{ + static void Main() + { + try + { + // Example locale – in real scenarios this could come from user input or a config file. + string locale = "de"; + + // Convert the locale string to a .NET CultureInfo instance. + CultureInfo culture = GetCultureInfoFromLocale(locale); + + // Prepare load options with the desired culture. + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx) + { + CultureInfo = culture + }; + + Workbook workbook; + + // Ensure the input file exists; otherwise create a new workbook. + const string inputPath = "input.xlsx"; + if (File.Exists(inputPath)) + { + workbook = new Workbook(inputPath, loadOptions); + } + else + { + workbook = new Workbook(loadOptions); + } + + // Apply globalization settings based on the locale. + workbook.Settings.GlobalizationSettings = CreateLocalizationSettings(locale); + + // Example operation: write the locale display name into a cell. + workbook.Worksheets[0].Cells["A1"].PutValue($"Locale: {culture.DisplayName}"); + + // Save the workbook. + workbook.Save("output.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + // Maps simple locale codes to full .NET culture identifiers. + static CultureInfo GetCultureInfoFromLocale(string locale) + { + return locale switch + { + "ar" => new CultureInfo("ar-SA"), + "bg" => new CultureInfo("bg-BG"), + "ca" => new CultureInfo("ca-ES"), + "cs" => new CultureInfo("cs-CZ"), + "da" => new CultureInfo("da-DK"), + "de" => new CultureInfo("de-DE"), + "el" => new CultureInfo("el-GR"), + "en" => new CultureInfo("en-US"), + "es" => new CultureInfo("es-ES"), + "fa" => new CultureInfo("fa-IR"), + "fr" => new CultureInfo("fr-FR"), + "he" => new CultureInfo("he-IL"), + "hi" => new CultureInfo("hi-IN"), + "hr" => new CultureInfo("hr-HR"), + "hu" => new CultureInfo("hu-HU"), + "id" => new CultureInfo("id-ID"), + "it" => new CultureInfo("it-IT"), + "ja" => new CultureInfo("ja-JP"), + "ka" => new CultureInfo("ka-GE"), + "ko" => new CultureInfo("ko-KR"), + "lt" => new CultureInfo("lt-LT"), + "ms" => new CultureInfo("ms-MY"), + "nl" => new CultureInfo("nl-NL"), + "pl" => new CultureInfo("pl-PL"), + "pt" => new CultureInfo("pt-PT"), + "ro" => new CultureInfo("ro-RO"), + "ru" => new CultureInfo("ru-RU"), + "sk" => new CultureInfo("sk-SK"), + "th" => new CultureInfo("th-TH"), + "tr" => new CultureInfo("tr-TR"), + "uk" => new CultureInfo("uk-UA"), + "vi" => new CultureInfo("vi-VN"), + "zh" => new CultureInfo("zh-CN"), + "zh-hant" => new CultureInfo("zh-TW"), + _ => CultureInfo.InvariantCulture, + }; + } + + // Returns a GlobalizationSettings instance. Adjust as needed for specific locales. + static GlobalizationSettings CreateLocalizationSettings(string locale) + { + // For demonstration, we return a default GlobalizationSettings instance. + // Customization per locale can be added here if required. + return new GlobalizationSettings(); + } +} \ No newline at end of file diff --git a/globalization-and-localization/load-the-excel-workbook-using-workbookload-after-configuring-the-custom-globalization-settings.cs b/globalization-and-localization/load-the-excel-workbook-using-workbookload-after-configuring-the-custom-globalization-settings.cs new file mode 100644 index 0000000000..f4d9eadd83 --- /dev/null +++ b/globalization-and-localization/load-the-excel-workbook-using-workbookload-after-configuring-the-custom-globalization-settings.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Path to the Excel file to be loaded + string inputPath = "input.xlsx"; + + // Create LoadOptions and configure custom globalization settings + LoadOptions loadOptions = new LoadOptions(); + // Example: use German culture (comma as decimal separator) + loadOptions.CultureInfo = new CultureInfo("de-DE"); + + // Load the workbook with the specified LoadOptions + Workbook workbook = new Workbook(inputPath, loadOptions); + + // Demonstrate that the culture settings are applied + Console.WriteLine("Cell A1 value with German culture: " + workbook.Worksheets[0].Cells["A1"].StringValue); + + // Save the workbook (optional) + workbook.Save("output.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/log-each-overridden-method-call-to-a-debug-file-for-troubleshooting-localization-behavior-at-runtime.cs b/globalization-and-localization/log-each-overridden-method-call-to-a-debug-file-for-troubleshooting-localization-behavior-at-runtime.cs new file mode 100644 index 0000000000..5dca047a00 --- /dev/null +++ b/globalization-and-localization/log-each-overridden-method-call-to-a-debug-file-for-troubleshooting-localization-behavior-at-runtime.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsLocalizationLogging +{ + // Custom globalization settings that logs each overridden method call + public class LoggingGlobalizationSettings : GlobalizationSettings + { + private readonly string _logFilePath; + + public LoggingGlobalizationSettings(string logDirectory) + { + // Ensure the log directory exists + Directory.CreateDirectory(logDirectory); + _logFilePath = Path.Combine(logDirectory, "LocalizationLog.txt"); + } + + // Helper to append a line to the log file with a timestamp + private void Log(string message) + { + string entry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} - {message}"; + File.AppendAllLines(_logFilePath, new[] { entry }); + } + + // Override to log calls for getting a localized function name + public override string GetLocalFunctionName(string standardName) + { + Log($"GetLocalFunctionName called with standardName=\"{standardName}\""); + // Use base implementation for actual behavior + return base.GetLocalFunctionName(standardName); + } + + // Override to log calls for getting a localized built‑in name + public override string GetLocalBuiltInName(string standardName) + { + Log($"GetLocalBuiltInName called with standardName=\"{standardName}\""); + return base.GetLocalBuiltInName(standardName); + } + + // Override to log calls for converting a localized built‑in name back to the standard name + public override string GetStandardBuiltInName(string localName) + { + Log($"GetStandardBuiltInName called with localName=\"{localName}\""); + return base.GetStandardBuiltInName(localName); + } + } + + public class Program + { + public static void Main() + { + // Create a new workbook (lifecycle rule: use provided creation logic) + Workbook workbook = new Workbook(); + + // Set up the logging globalization settings + string logDir = Path.Combine(Environment.CurrentDirectory, "Logs"); + workbook.Settings.GlobalizationSettings = new LoggingGlobalizationSettings(logDir); + + // Sample data to trigger localization methods + Worksheet sheet = workbook.Worksheets[0]; + sheet.Cells["A1"].PutValue(10); + sheet.Cells["A2"].PutValue(20); + sheet.Cells["A3"].PutValue(30); + + // Use a standard function name – this will invoke GetLocalFunctionName internally + sheet.Cells["B1"].Formula = "=SUM(A1:A3)"; + + // Use a built‑in name that may be localized – this will invoke GetLocalBuiltInName + // For demonstration, we call the method directly + var settings = (LoggingGlobalizationSettings)workbook.Settings.GlobalizationSettings; + string localName = settings.GetLocalBuiltInName("Total"); + + // Use the returned local name in a formula to cause GetStandardBuiltInName later + sheet.Cells["B2"].Formula = $"={localName}(A1:A3)"; + + // Calculate formulas to ensure all methods are exercised + workbook.CalculateFormula(); + + // Save the workbook (lifecycle rule: use provided save logic) + string outputPath = Path.Combine(Environment.CurrentDirectory, "LocalizedWorkbook.xlsx"); + workbook.Save(outputPath); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/log-performance-metrics-for-each-localization-step-during-batch-processing-to-identify-bottlenecks.cs b/globalization-and-localization/log-performance-metrics-for-each-localization-step-during-batch-processing-to-identify-bottlenecks.cs new file mode 100644 index 0000000000..0eb1d0f55b --- /dev/null +++ b/globalization-and-localization/log-performance-metrics-for-each-localization-step-during-batch-processing-to-identify-bottlenecks.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsPerformanceLogging +{ + class Program + { + static void Main() + { + try + { + // Stopwatch to measure each step + Stopwatch sw = new Stopwatch(); + + // 1. Load workbook (template) + const string templatePath = "Template.xlsx"; // replace with actual template path + if (!File.Exists(templatePath)) + { + Console.WriteLine($"Template file not found: {templatePath}"); + return; + } + + sw.Start(); + Workbook workbook = new Workbook(templatePath); + sw.Stop(); + Console.WriteLine($"Load workbook: {sw.ElapsedMilliseconds} ms"); + sw.Reset(); + + // 2. Prepare data source for smart markers + sw.Start(); + var employees = new List + { + new Employee { Name = "John Doe", Age = 30, Department = "Sales" }, + new Employee { Name = "Jane Smith", Age = 28, Department = "HR" } + }; + sw.Stop(); + Console.WriteLine($"Prepare data source: {sw.ElapsedMilliseconds} ms"); + sw.Reset(); + + // 3. Set up WorkbookDesigner and assign data source + sw.Start(); + WorkbookDesigner designer = new WorkbookDesigner + { + Workbook = workbook, + LineByLine = false // using range smart markers + }; + designer.SetDataSource("Employees", employees); + sw.Stop(); + Console.WriteLine($"Configure designer & set data source: {sw.ElapsedMilliseconds} ms"); + sw.Reset(); + + // 4. Process smart markers (localization step) + sw.Start(); + designer.Process(); // processes all smart markers in the defined range + sw.Stop(); + Console.WriteLine($"Process smart markers: {sw.ElapsedMilliseconds} ms"); + sw.Reset(); + + // 5. Optional: calculate formulas with a custom monitor to log each cell calculation + sw.Start(); + CalculationOptions calcOptions = new CalculationOptions + { + CalculationMonitor = new PerformanceCalculationMonitor() + }; + workbook.CalculateFormula(calcOptions); + sw.Stop(); + Console.WriteLine($"Calculate formulas: {sw.ElapsedMilliseconds} ms"); + sw.Reset(); + + // 6. Save the resulting workbook + const string resultPath = "Result.xlsx"; // replace with desired output path + sw.Start(); + workbook.Save(resultPath); + sw.Stop(); + Console.WriteLine($"Save workbook: {sw.ElapsedMilliseconds} ms"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Sample data class used for smart markers + public class Employee + { + public string Name { get; set; } + public int Age { get; set; } + public string Department { get; set; } + } + + // Custom calculation monitor to log each cell calculation (optional performance insight) + public class PerformanceCalculationMonitor : AbstractCalculationMonitor + { + public override void BeforeCalculate(int sheetIndex, int rowIndex, int columnIndex) + { + // Placeholder for per‑cell timing if needed + } + + public override void AfterCalculate(int sheetIndex, int rowIndex, int columnIndex) + { + // Log after each cell is calculated (commented out to avoid excessive output) + // Console.WriteLine($"Calculated Sheet{sheetIndex} Row{rowIndex} Col{columnIndex}"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/measure-performance-differences-when-loading-workbooks-with-and-without-custom-globalizationsettings-applied.cs b/globalization-and-localization/measure-performance-differences-when-loading-workbooks-with-and-without-custom-globalizationsettings-applied.cs new file mode 100644 index 0000000000..8989c8a38b --- /dev/null +++ b/globalization-and-localization/measure-performance-differences-when-loading-workbooks-with-and-without-custom-globalizationsettings-applied.cs @@ -0,0 +1,80 @@ +using System; +using System.Diagnostics; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsPerformanceDemo +{ + // Custom globalization settings – overrides boolean display strings + public class CustomGlobalizationSettings : GlobalizationSettings + { + public override string GetBooleanValueString(bool value) + { + return value ? "TRUE_CUSTOM" : "FALSE_CUSTOM"; + } + } + + public class Program + { + // Path for the sample workbook + private const string SampleFile = "sample.xlsx"; + + public static void Main() + { + // Ensure a sample workbook exists + CreateSampleWorkbook(); + + // Measure load time without custom globalization settings + TimeSpan defaultLoadTime = MeasureLoadTime(applyCustomSettings: false); + Console.WriteLine($"Load time without custom globalization settings: {defaultLoadTime.TotalMilliseconds} ms"); + + // Measure load time with custom globalization settings + TimeSpan customLoadTime = MeasureLoadTime(applyCustomSettings: true); + Console.WriteLine($"Load time with custom globalization settings: {customLoadTime.TotalMilliseconds} ms"); + } + + // Creates a workbook with a sizable amount of data to make loading measurable + private static void CreateSampleWorkbook() + { + Workbook wb = new Workbook(); + Worksheet sheet = wb.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate 10,000 rows with sample data + for (int row = 0; row < 10000; row++) + { + cells[row, 0].PutValue($"Item {row}"); + cells[row, 1].PutValue(row); + cells[row, 2].PutValue(row % 2 == 0); + } + + // Save the workbook (uses the provided save rule) + wb.Save(SampleFile); + } + + // Loads the workbook and optionally applies custom globalization settings, + // returning the elapsed time for the operation. + private static TimeSpan MeasureLoadTime(bool applyCustomSettings) + { + Stopwatch sw = new Stopwatch(); + + // Start timing + sw.Start(); + + // Load the workbook using the standard constructor (provided load rule) + Workbook wb = new Workbook(SampleFile); + + // Apply custom globalization settings after loading if requested + if (applyCustomSettings) + { + wb.Settings.GlobalizationSettings = new CustomGlobalizationSettings(); + } + + // Stop timing + sw.Stop(); + + // Return elapsed time + return sw.Elapsed; + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/measure-performance-impact-of-applying-custom-globalization-settings-versus-default-settings-when-generating-large-pivot-tables.cs b/globalization-and-localization/measure-performance-impact-of-applying-custom-globalization-settings-versus-default-settings-when-generating-large-pivot-tables.cs new file mode 100644 index 0000000000..a39b1e404e --- /dev/null +++ b/globalization-and-localization/measure-performance-impact-of-applying-custom-globalization-settings-versus-default-settings-when-generating-large-pivot-tables.cs @@ -0,0 +1,154 @@ +using System; +using System.Diagnostics; +using Aspose.Cells; +using Aspose.Cells.Pivot; +using Aspose.Cells.Settings; + +namespace AsposeCellsPerformanceDemo +{ + // Custom globalization settings for pivot tables + public class CustomPivotGlobalizationSettings : PivotGlobalizationSettings + { + public override string GetTextOfTotal() + { + return "Custom Total"; + } + + public override string GetTextOfGrandTotal() + { + return "Custom Grand Total"; + } + + public override string GetTextOfDataFieldHeader() + { + return "Custom Data Header"; + } + + public override string GetTextOfProtectedName(string protectedName) + { + return protectedName + "_Custom"; + } + } + + class Program + { + static void Main() + { + // Parameters for large dataset + const int rowCount = 100_000; // number of data rows + const int colCount = 5; // number of data columns (including row header) + + // Measure default globalization performance + Stopwatch swDefault = Stopwatch.StartNew(); + Workbook wbDefault = CreateWorkbookWithPivot(rowCount, colCount, useCustomSettings: false); + swDefault.Stop(); + + // Measure custom globalization performance + Stopwatch swCustom = Stopwatch.StartNew(); + Workbook wbCustom = CreateWorkbookWithPivot(rowCount, colCount, useCustomSettings: true); + swCustom.Stop(); + + // Output results + Console.WriteLine($"Default globalization time: {swDefault.ElapsedMilliseconds} ms"); + Console.WriteLine($"Custom globalization time: {swCustom.ElapsedMilliseconds} ms"); + + // Save workbooks (optional, just to verify correctness) + wbDefault.Save("Pivot_Default.xlsx"); + wbCustom.Save("Pivot_Custom.xlsx"); + } + + /// + /// Creates a workbook, fills it with sample data, applies optional custom globalization, + /// adds a pivot table, refreshes and calculates it. + /// + /// Number of data rows to generate. + /// Number of data columns (including the first column for row field). + /// If true, applies custom pivot globalization settings. + /// The populated workbook. + private static Workbook CreateWorkbookWithPivot(int rows, int cols, bool useCustomSettings) + { + // Create a new workbook + Workbook workbook = new Workbook(); + Worksheet dataSheet = workbook.Worksheets[0]; + Cells cells = dataSheet.Cells; + + // Populate header row + for (int c = 0; c < cols; c++) + { + cells[0, c].PutValue($"Field{c + 1}"); + } + + // Populate large dataset + Random rnd = new Random(0); + for (int r = 1; r <= rows; r++) + { + // First column: categorical data (e.g., "CategoryA" to "CategoryZ") + string category = "Category" + ((r - 1) % 26); + cells[r, 0].PutValue(category); + + // Remaining columns: numeric data + for (int c = 1; c < cols; c++) + { + cells[r, c].PutValue(rnd.NextDouble() * 1000); + } + } + + // Apply custom globalization settings if requested + if (useCustomSettings) + { + // Create an instance of custom pivot settings + CustomPivotGlobalizationSettings pivotSettings = new CustomPivotGlobalizationSettings(); + + // Assign to workbook's globalization settings + workbook.Settings.GlobalizationSettings = new GlobalizationSettings(); + workbook.Settings.GlobalizationSettings.PivotSettings = pivotSettings; + } + + // Define the data range for the pivot table + string dataRange = $"A1:{CellIndexToName(rows, cols - 1)}"; + + // Add a new worksheet for the pivot table + Worksheet pivotSheet = workbook.Worksheets.Add("PivotTable"); + + // Add the pivot table + int pivotIndex = pivotSheet.PivotTables.Add(dataRange, "A1", "LargePivot"); + PivotTable pivotTable = pivotSheet.PivotTables[pivotIndex]; + + // Add the first column as row field + pivotTable.AddFieldToArea(PivotFieldType.Row, 0); + + // Add all numeric columns as data fields + for (int c = 1; c < cols; c++) + { + pivotTable.AddFieldToArea(PivotFieldType.Data, c); + } + + // Refresh and calculate the pivot table to materialize it + pivotTable.RefreshData(); + pivotTable.CalculateData(); + + return workbook; + } + + /// + /// Converts zero‑based row and column indexes to an Excel cell name (e.g., (0,0) => "A1"). + /// Used to build the data range string. + /// + private static string CellIndexToName(int rowIndex, int columnIndex) + { + // Convert column index to letters + string columnName = ""; + int dividend = columnIndex + 1; + while (dividend > 0) + { + int modulo = (dividend - 1) % 26; + columnName = Convert.ToChar('A' + modulo) + columnName; + dividend = (dividend - modulo) / 26; + } + + // Excel rows are 1‑based + int excelRow = rowIndex + 1; + return $"{columnName}{excelRow}"; + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/override-getbooleanstring-to-return-localized-truefalse-strings-for-the-selected-locale.cs b/globalization-and-localization/override-getbooleanstring-to-return-localized-truefalse-strings-for-the-selected-locale.cs new file mode 100644 index 0000000000..8d95d2ffab --- /dev/null +++ b/globalization-and-localization/override-getbooleanstring-to-return-localized-truefalse-strings-for-the-selected-locale.cs @@ -0,0 +1,76 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsDemo +{ + // Custom globalization settings that return locale‑specific boolean strings + public class CustomBooleanGlobalizationSettings : GlobalizationSettings + { + private readonly CultureInfo _culture; + + public CustomBooleanGlobalizationSettings(CultureInfo culture) + { + _culture = culture; + } + + // Override to provide localized true/false strings + public override string GetBooleanValueString(bool bv) + { + // French example + if (_culture.Name.StartsWith("fr", StringComparison.OrdinalIgnoreCase)) + return bv ? "Vrai" : "Faux"; + + // German example + if (_culture.Name.StartsWith("de", StringComparison.OrdinalIgnoreCase)) + return bv ? "Wahr" : "Falsch"; + + // Default to English + return bv ? "True" : "False"; + } + } + + // Demonstration of applying the custom settings to a workbook + public class BooleanLocalizationDemo + { + public static void Run() + { + try + { + // Select the desired locale (e.g., French - France) + CultureInfo locale = new CultureInfo("fr-FR"); + + // Create a new workbook + Workbook workbook = new Workbook(); + + // Assign the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = new CustomBooleanGlobalizationSettings(locale); + + // Access the first worksheet + Worksheet sheet = workbook.Worksheets[0]; + + // Insert boolean values into cells + sheet.Cells["A1"].PutValue(true); + sheet.Cells["A2"].PutValue(false); + + // Save the workbook (the boolean strings will appear according to the locale) + string outputPath = "BooleanLocalizationDemo.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } + + // Entry point required for console application + public class Program + { + public static void Main(string[] args) + { + BooleanLocalizationDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/override-geterrorstring-in-the-custom-class-to-provide-localized-error-messages-for-excel-errors.cs b/globalization-and-localization/override-geterrorstring-in-the-custom-class-to-provide-localized-error-messages-for-excel-errors.cs new file mode 100644 index 0000000000..927a6d3f78 --- /dev/null +++ b/globalization-and-localization/override-geterrorstring-in-the-custom-class-to-provide-localized-error-messages-for-excel-errors.cs @@ -0,0 +1,76 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + // Custom globalization settings that provide localized error messages + public class CustomErrorGlobalizationSettings : GlobalizationSettings + { + // Override to map default error strings to custom localized strings + public override string GetErrorValueString(string err) + { + // Map specific Excel error codes to custom messages + return err switch + { + "#DIV/0!" => "Custom Division Error", + "#VALUE!" => "Custom Type Mismatch", + "#NAME?" => "Custom Identifier Error", + "#N/A" => "Custom Not Available", + "#REF!" => "Custom Reference Error", + _ => base.GetErrorValueString(err) // Fallback to default behavior + }; + } + } + + public class GlobalizationSettingsGetErrorValueStringDemo + { + public static void Run() + { + try + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Apply the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = new CustomErrorGlobalizationSettings(); + + // Access the first worksheet + Worksheet worksheet = workbook.Worksheets[0]; + Cells cells = worksheet.Cells; + + // Create several error scenarios + cells["A1"].Formula = "=1/0"; // #DIV/0! + cells["A2"].Formula = "=SUM(\"text\")"; // #VALUE! + cells["A3"].Formula = "=UNKNOWNFUNC()"; // #NAME? + cells["A4"].Formula = "=VLOOKUP(1,B1:C1,2,FALSE)"; // #N/A (if not found) + cells["A5"].Formula = "=INDIRECT(\"Z1000\")"; // #REF! + + // Calculate formulas to generate the errors + workbook.CalculateFormula(); + + // Display the custom error strings for each cell + Console.WriteLine($"A1 error display: {cells["A1"].DisplayStringValue}"); + Console.WriteLine($"A2 error display: {cells["A2"].DisplayStringValue}"); + Console.WriteLine($"A3 error display: {cells["A3"].DisplayStringValue}"); + Console.WriteLine($"A4 error display: {cells["A4"].DisplayStringValue}"); + Console.WriteLine($"A5 error display: {cells["A5"].DisplayStringValue}"); + + // Save the workbook to verify that custom settings do not affect file content + workbook.Save("CustomErrorGlobalizationDemo.xlsx"); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Entry point for the application + public static class Program + { + public static void Main() + { + GlobalizationSettingsGetErrorValueStringDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/program-a-macrolike-routine-that-adds-subtotals-with-localized-labels-to-all-worksheets-in-a-workbook.cs b/globalization-and-localization/program-a-macrolike-routine-that-adds-subtotals-with-localized-labels-to-all-worksheets-in-a-workbook.cs new file mode 100644 index 0000000000..16c60ac85c --- /dev/null +++ b/globalization-and-localization/program-a-macrolike-routine-that-adds-subtotals-with-localized-labels-to-all-worksheets-in-a-workbook.cs @@ -0,0 +1,62 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Settings; + +class Program +{ + static void Main() + { + // Create a new workbook with three worksheets + Workbook workbook = new Workbook(); + workbook.Worksheets.Add(); // Sheet2 + workbook.Worksheets.Add(); // Sheet3 + + // Apply custom globalization settings to change the total label for the Sum function + SettableGlobalizationSettings globalization = new SettableGlobalizationSettings(); + globalization.SetTotalName(ConsolidationFunction.Sum, "Localized Sum"); + workbook.Settings.GlobalizationSettings = globalization; + + // Populate each worksheet with sample data and add subtotals + for (int wsIndex = 0; wsIndex < workbook.Worksheets.Count; wsIndex++) + { + Worksheet sheet = workbook.Worksheets[wsIndex]; + Cells cells = sheet.Cells; + + // Sample header + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Amount"); + + // Sample rows (5 rows per sheet) + object[,] data = new object[,] + { + { "Group A", 1200 }, + { "Group A", 800 }, + { "Group B", 1500 }, + { "Group B", 700 }, + { "Group C", 900 } + }; + + for (int r = 0; r < data.GetLength(0); r++) + { + cells[r + 1, 0].PutValue(data[r, 0]); // Category column + cells[r + 1, 1].PutValue(data[r, 1]); // Amount column + } + + // Define the range that contains the data (including header) + int startRow = 0; + int startCol = 0; + int endRow = data.GetLength(0); // includes header row + int endCol = 1; + CellArea area = CellArea.CreateCellArea(startRow, startCol, endRow, endCol); + + // Add subtotals: + // - Group by the first column (Category) + // - Use SUM function on the second column (Amount) + // - Replace existing subtotals, no page breaks, summary placed below data + cells.Subtotal(area, 0, ConsolidationFunction.Sum, new int[] { 1 }, true, false, true); + } + + // Save the workbook + workbook.Save("AllSheetsWithLocalizedSubtotals.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/programmatically-set-worksheet-cell-styles-to-display-dates-in-japanese-era-format-after-conversion-then-export-to-pdf.cs b/globalization-and-localization/programmatically-set-worksheet-cell-styles-to-display-dates-in-japanese-era-format-after-conversion-then-export-to-pdf.cs new file mode 100644 index 0000000000..8317e47bc1 --- /dev/null +++ b/globalization-and-localization/programmatically-set-worksheet-cell-styles-to-display-dates-in-japanese-era-format-after-conversion-then-export-to-pdf.cs @@ -0,0 +1,44 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Rendering; + +namespace AsposeCellsJapaneseEraPdf +{ + class Program + { + static void Main() + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + + // Set the regional settings to Japan so that Japanese era formatting can be applied + // (uses WorkbookSettings.Region property) + workbook.Settings.Region = CountryCode.Japan; + + // Access the first worksheet and a target cell + Worksheet sheet = workbook.Worksheets[0]; + Cell cell = sheet.Cells[0, 0]; // A1 + + // Put an Excel serial date value (e.g., 44089 corresponds to 2020-09-15) + cell.PutValue(44089); + + // Retrieve the cell's style, set a custom format that displays the date in Japanese era + // The format string uses the locale identifier for Japanese ([$-F800]) + Style style = cell.GetStyle(); + style.Custom = "[$-F800]ggge\"年\"m\"月\"d\"日\""; // Example: Reiwa3年9月15日 + cell.SetStyle(style); + + // Configure PDF save options, specifying a Japanese font to ensure proper rendering + PdfSaveOptions pdfOptions = new PdfSaveOptions + { + DefaultFont = "MS Gothic", // Japanese font + CheckWorkbookDefaultFont = true + }; + + // Save the workbook as PDF (lifecycle: save) + workbook.Save("JapaneseEraDate.pdf", pdfOptions); + + Console.WriteLine("PDF generated with Japanese era date formatting."); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/provide-documentation-examples-showing-how-to-toggle-between-english-and-localized-function-names-using-formulalocal.cs b/globalization-and-localization/provide-documentation-examples-showing-how-to-toggle-between-english-and-localized-function-names-using-formulalocal.cs new file mode 100644 index 0000000000..71f174e78b --- /dev/null +++ b/globalization-and-localization/provide-documentation-examples-showing-how-to-toggle-between-english-and-localized-function-names-using-formulalocal.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsExamples +{ + public class ToggleFormulaLocalizationDemo + { + public static void Run() + { + try + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Set the workbook region to Germany to demonstrate German localization + workbook.Settings.Region = CountryCode.Germany; + + // Create customizable globalization settings + SettableGlobalizationSettings gSettings = new SettableGlobalizationSettings(); + + // Map the standard English function name "SUM" to the German name "SUMME" + // The bidirectional flag makes the mapping work both ways + gSettings.SetLocalFunctionName("SUM", "SUMME", true); + + // Apply the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = gSettings; + + // ------------------------------------------------------------ + // 1. Use the standard (English) function name in a formula + // ------------------------------------------------------------ + Cell cellEnglish = sheet.Cells["A1"]; + cellEnglish.Formula = "=SUM(B1:B3)"; + + // Populate the source range + sheet.Cells["B1"].PutValue(10); + sheet.Cells["B2"].PutValue(20); + sheet.Cells["B3"].PutValue(30); + + Console.WriteLine("Standard Formula (English): " + cellEnglish.Formula); + Console.WriteLine("Localized Formula (German): " + cellEnglish.FormulaLocal); + + // ------------------------------------------------------------ + // 2. Use the localized (German) function name via FormulaLocal + // ------------------------------------------------------------ + Cell cellLocalized = sheet.Cells["A2"]; + cellLocalized.FormulaLocal = "=SUMME(C1:C3)"; + + // Populate the source range for the second formula + sheet.Cells["C1"].PutValue(5); + sheet.Cells["C2"].PutValue(15); + sheet.Cells["C3"].PutValue(25); + + Console.WriteLine("Localized Formula (German) set via FormulaLocal: " + cellLocalized.FormulaLocal); + Console.WriteLine("Standard Formula (English) derived from localized: " + cellLocalized.Formula); + + // ------------------------------------------------------------ + // Calculate all formulas to verify correctness + // ------------------------------------------------------------ + workbook.CalculateFormula(); + + Console.WriteLine("Result of A1 (SUM): " + cellEnglish.Value); + Console.WriteLine("Result of A2 (SUMME): " + cellLocalized.Value); + + // Save the workbook to verify the formulas are stored correctly + string outputPath = "ToggleFormulaLocalizationDemo.xlsx"; + + // Ensure the output directory exists + string outputDir = Path.GetDirectoryName(Path.GetFullPath(outputPath)); + if (!Directory.Exists(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to {Path.GetFullPath(outputPath)}"); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + ToggleFormulaLocalizationDemo.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/save-the-localized-workbook-as-xlsx-preserving-original-formatting-comments-and-cell-styles.cs b/globalization-and-localization/save-the-localized-workbook-as-xlsx-preserving-original-formatting-comments-and-cell-styles.cs new file mode 100644 index 0000000000..9ac090dc47 --- /dev/null +++ b/globalization-and-localization/save-the-localized-workbook-as-xlsx-preserving-original-formatting-comments-and-cell-styles.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using Aspose.Cells; + +namespace AsposeCellsLocalizationSave +{ + class Program + { + static void Main() + { + // Path to the source workbook that contains localized content, + // formatting, comments, and cell styles. + string sourcePath = "LocalizedInput.xlsx"; + + // Verify that the source file exists to avoid FileNotFoundException. + if (!File.Exists(sourcePath)) + { + Console.WriteLine($"Error: Source file '{sourcePath}' not found."); + return; + } + + try + { + // Load the existing workbook. The constructor with a file path + // utilizes the built‑in load rule. + Workbook workbook = new Workbook(sourcePath); + + // Save the workbook as XLSX while preserving all original + // formatting, comments, and styles. + string outputPath = "LocalizedOutput.xlsx"; + workbook.Save(outputPath, SaveFormat.Xlsx); + + Console.WriteLine($"Workbook saved successfully to '{outputPath}'."); + } + catch (Exception ex) + { + // Catch any runtime exceptions (e.g., loading/saving errors) and display a message. + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/save-the-workbook-containing-japanese-era-dates-as-pdf-confirming-era-symbols-appear-correctly-in-the-output.cs b/globalization-and-localization/save-the-workbook-containing-japanese-era-dates-as-pdf-confirming-era-symbols-appear-correctly-in-the-output.cs new file mode 100644 index 0000000000..aef86054c6 --- /dev/null +++ b/globalization-and-localization/save-the-workbook-containing-japanese-era-dates-as-pdf-confirming-era-symbols-appear-correctly-in-the-output.cs @@ -0,0 +1,33 @@ +using System; +using Aspose.Cells; + +class JapaneseEraPdfDemo +{ + static void Main() + { + // Create a new workbook + Workbook wb = new Workbook(); + + // Set the workbook's regional settings to Japan (required for era formatting) + wb.Settings.Region = CountryCode.Japan; + + // Insert a serial date value (e.g., 44089 corresponds to 2020-09-15) + Cell cell = wb.Worksheets[0].Cells[0, 0]; + cell.PutValue(44089); + + // Apply a custom format that displays the Japanese era (e.g., "令和2年9月15日") + Style style = cell.GetStyle(); + style.Custom = "[$-F800]yyyy年m月d日"; + cell.SetStyle(style); + + // Configure PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + // Use a Japanese font to ensure era symbols render correctly + pdfOptions.DefaultFont = "MS Gothic"; + // Try to use the workbook's default font first + pdfOptions.CheckWorkbookDefaultFont = true; + + // Save the workbook as PDF + wb.Save("JapaneseEra.pdf", pdfOptions); + } +} \ No newline at end of file diff --git a/globalization-and-localization/set-cell-formulas-with-cellformulalocal-to-apply-localized-function-names-during-workbook-processing.cs b/globalization-and-localization/set-cell-formulas-with-cellformulalocal-to-apply-localized-function-names-during-workbook-processing.cs new file mode 100644 index 0000000000..bea9cb1b6d --- /dev/null +++ b/globalization-and-localization/set-cell-formulas-with-cellformulalocal-to-apply-localized-function-names-during-workbook-processing.cs @@ -0,0 +1,50 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Tables; + +namespace AsposeCellsLocalizedFormulaDemo +{ + class Program + { + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Set the workbook region to Germany to demonstrate German localization + workbook.Settings.Region = CountryCode.Germany; + + // Access the first worksheet and its cells collection + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Populate some sample data that will be used by the formulas + cells["B1"].PutValue(10); + cells["C1"].PutValue(20); + cells["B2"].PutValue(5); + cells["C2"].PutValue(15); + + // Set a formula using the standard (English) function name + Cell standardFormulaCell = cells["A1"]; + standardFormulaCell.Formula = "=SUM(B1:C1)"; + + // Set a formula using the localized (German) function name via FormulaLocal property + Cell localizedFormulaCell = cells["A2"]; + localizedFormulaCell.FormulaLocal = "=SUMME(B2:C2)"; + + // Display both formulas to verify the difference + Console.WriteLine("Standard formula (English): " + standardFormulaCell.Formula); + Console.WriteLine("Localized formula (German): " + localizedFormulaCell.FormulaLocal); + + // Calculate all formulas in the workbook + workbook.CalculateFormula(); + + // Output the calculated results + Console.WriteLine("Result of standard formula (A1): " + standardFormulaCell.Value); + Console.WriteLine("Result of localized formula (A2): " + localizedFormulaCell.Value); + + // Save the workbook to a file + workbook.Save("LocalizedFormulaDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/test-that-excels-autofilter-works-correctly-with-localized-column-headers-after-applying-globalization.cs b/globalization-and-localization/test-that-excels-autofilter-works-correctly-with-localized-column-headers-after-applying-globalization.cs new file mode 100644 index 0000000000..27487d6cf9 --- /dev/null +++ b/globalization-and-localization/test-that-excels-autofilter-works-correctly-with-localized-column-headers-after-applying-globalization.cs @@ -0,0 +1,50 @@ +using System; +using Aspose.Cells; + +class AutoFilterLocalizationTest +{ + 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; + + // Apply custom globalization settings (optional, demonstrates usage) + SettableGlobalizationSettings globalization = new SettableGlobalizationSettings(); + globalization.SetListSeparator(';'); // Example: change list separator + workbook.Settings.GlobalizationSettings = globalization; + + // Localized column headers (e.g., French) + cells["A1"].PutValue("Produit"); // "Product" + cells["B1"].PutValue("Ventes"); // "Sales" + + // Sample data with localized product names + cells["A2"].PutValue("Pomme"); // Apple + cells["B2"].PutValue(120); + cells["A3"].PutValue("Banane"); // Banana + cells["B3"].PutValue(80); + cells["A4"].PutValue("Orange"); + cells["B4"].PutValue(150); + cells["A5"].PutValue("Pomme"); // Apple again + cells["B5"].PutValue(200); + + // Define the autofilter range that includes the header row and data rows + worksheet.AutoFilter.Range = "A1:B5"; + + // Apply a filter on the first column (Produit) for the localized value "Pomme" + worksheet.AutoFilter.Filter(0, "Pomme"); + worksheet.AutoFilter.Refresh(); + + // Verify which rows are hidden after filtering + // Row indices are zero‑based; row 0 is the header. + for (int row = 1; row <= 5; row++) // rows 1‑5 correspond to Excel rows 2‑6 + { + bool isHidden = worksheet.Cells.Rows[row].IsHidden; + Console.WriteLine($"Row {row + 1} hidden: {isHidden}"); + } + + // Save the workbook to verify the filter result + workbook.Save("AutoFilterLocalizationTest.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/test-that-overriding-getgrandtotalname-does-not-affect-subtotal-labels-when-both-custom-settings-are-applied-simultaneously.cs b/globalization-and-localization/test-that-overriding-getgrandtotalname-does-not-affect-subtotal-labels-when-both-custom-settings-are-applied-simultaneously.cs new file mode 100644 index 0000000000..92e30b60dc --- /dev/null +++ b/globalization-and-localization/test-that-overriding-getgrandtotalname-does-not-affect-subtotal-labels-when-both-custom-settings-are-applied-simultaneously.cs @@ -0,0 +1,69 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Pivot; + +namespace AsposeCellsExamples +{ + public class TestGrandTotalAndSubtotalLabels + { + public static void Run() + { + try + { + // ---------- Create workbook and sample data ---------- + var workbook = new Workbook(); + var sheet = workbook.Worksheets[0]; + var cells = sheet.Cells; + + // Header + cells["A1"].PutValue("Category"); + cells["B1"].PutValue("Sales"); + + // Data rows + cells["A2"].PutValue("North"); + cells["B2"].PutValue(1000); + cells["A3"].PutValue("North"); + cells["B3"].PutValue(1500); + cells["A4"].PutValue("South"); + cells["B4"].PutValue(2000); + cells["A5"].PutValue("South"); + cells["B5"].PutValue(2500); + + // ---------- Create pivot table ---------- + // The pivot table will be placed starting at cell D1. + int pivotIndex = sheet.PivotTables.Add("A1:B5", "D1", "PivotTable1"); + var pivot = sheet.PivotTables[pivotIndex]; + + // Row field: Category + pivot.AddFieldToArea(PivotFieldType.Row, 0); + // Data field: Sales (default function is Sum) + pivot.AddFieldToArea(PivotFieldType.Data, 1); + + // Refresh and calculate to generate the pivot data. + pivot.RefreshData(); + pivot.CalculateData(); + + // ---------- Output verification ---------- + Console.WriteLine("Pivot table created successfully."); + + // ---------- Save the workbook ---------- + string outputPath = "GrandTotalAndSubtotalTest.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } + } + } + + // Entry point + class Program + { + static void Main() + { + TestGrandTotalAndSubtotalLabels.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/use-workbooksettings-to-enable-automatic-recalculation-after-applying-localized-formulas-to-ensure-correct-results.cs b/globalization-and-localization/use-workbooksettings-to-enable-automatic-recalculation-after-applying-localized-formulas-to-ensure-correct-results.cs new file mode 100644 index 0000000000..4989223664 --- /dev/null +++ b/globalization-and-localization/use-workbooksettings-to-enable-automatic-recalculation-after-applying-localized-formulas-to-ensure-correct-results.cs @@ -0,0 +1,41 @@ +using System; +using Aspose.Cells; + +class Program +{ + static void Main() + { + // Create a new workbook + Workbook workbook = new Workbook(); + + // Set the workbook region to a locale (e.g., German) to work with localized formulas + workbook.Settings.Region = CountryCode.Germany; + + // Access the first worksheet and its cells + Worksheet sheet = workbook.Worksheets[0]; + Cells cells = sheet.Cells; + + // Put sample values that the formula will use + cells["B1"].PutValue(5); + cells["C1"].PutValue(7); + + // Set a formula using the locale‑specific syntax (German SUMME) + cells["A1"].FormulaLocal = "=SUMME(B1:C1)"; + + // Enable automatic recalculation so that formulas are evaluated after changes + workbook.Settings.FormulaSettings.CalculationMode = CalcModeType.Automatic; + + // Optional: ensure calculation occurs when the workbook is opened or saved + workbook.Settings.FormulaSettings.CalculateOnOpen = true; + workbook.Settings.FormulaSettings.CalculateOnSave = true; + + // Perform calculation immediately to obtain the result + workbook.CalculateFormula(); + + // Display the calculated value + Console.WriteLine("A1 result: " + cells["A1"].Value); + + // Save the workbook + workbook.Save("LocalizedFormula.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/validate-that-boolean-values-display-localized-truefalse-strings-in-cells-containing-logical-formulas.cs b/globalization-and-localization/validate-that-boolean-values-display-localized-truefalse-strings-in-cells-containing-logical-formulas.cs new file mode 100644 index 0000000000..68cbf971c5 --- /dev/null +++ b/globalization-and-localization/validate-that-boolean-values-display-localized-truefalse-strings-in-cells-containing-logical-formulas.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsBooleanLocalizationDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // Create custom globalization settings with localized boolean strings + SettableGlobalizationSettings globalization = new SettableGlobalizationSettings(); + globalization.SetBooleanValueString(true, "VRAI"); // French for TRUE + globalization.SetBooleanValueString(false, "FAUX"); // French for FALSE + + // Apply the custom settings to the workbook + workbook.Settings.GlobalizationSettings = globalization; + + // Insert logical formulas that evaluate to boolean values + worksheet.Cells["A1"].Formula = "=1<2"; // evaluates to TRUE + worksheet.Cells["A2"].Formula = "=1>2"; // evaluates to FALSE + + // Calculate formulas so that BoolValue and StringValue are populated + workbook.CalculateFormula(); + + // Retrieve the boolean values from the cells + bool boolA1 = worksheet.Cells["A1"].BoolValue; + bool boolA2 = worksheet.Cells["A2"].BoolValue; + + // Get the localized display strings using the globalization settings + string localizedA1 = globalization.GetBooleanValueString(boolA1); + string localizedA2 = globalization.GetBooleanValueString(boolA2); + + // Also retrieve the string representation directly from the cells + string cellStringA1 = worksheet.Cells["A1"].StringValue; + string cellStringA2 = worksheet.Cells["A2"].StringValue; + + // Output the results for verification + Console.WriteLine($"Cell A1 BoolValue: {boolA1}, Localized via settings: {localizedA1}, Cell StringValue: {cellStringA1}"); + Console.WriteLine($"Cell A2 BoolValue: {boolA2}, Localized via settings: {localizedA2}, Cell StringValue: {cellStringA2}"); + + // Save the workbook (demonstrates that the localized strings are persisted) + workbook.Save("BooleanLocalizationDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/validate-that-number-formatting-respects-the-loaded-cultureinfo-by-comparing-cell-values-before-and-after-workbook-load.cs b/globalization-and-localization/validate-that-number-formatting-respects-the-loaded-cultureinfo-by-comparing-cell-values-before-and-after-workbook-load.cs new file mode 100644 index 0000000000..3e2bd44697 --- /dev/null +++ b/globalization-and-localization/validate-that-number-formatting-respects-the-loaded-cultureinfo-by-comparing-cell-values-before-and-after-workbook-load.cs @@ -0,0 +1,64 @@ +using System; +using System.Globalization; +using Aspose.Cells; + +namespace AsposeCellsCultureValidation +{ + class Program + { + static void Main() + { + // Define the culture to be used for formatting (German - uses comma as decimal separator) + CultureInfo germanCulture = new CultureInfo("de-DE"); + + // -------------------- Create workbook -------------------- + Workbook workbook = new Workbook(); + + // Apply the culture to the workbook settings + workbook.Settings.CultureInfo = germanCulture; + + // Access the first worksheet and target cell + Worksheet sheet = workbook.Worksheets[0]; + Cell cell = sheet.Cells["A1"]; + + // Put a numeric value into the cell + double numericValue = 1234.56; + cell.PutValue(numericValue); + + // Create a style with a built‑in decimal format that includes grouping + Style style = workbook.CreateStyle(); + style.Number = 4; // "#,##0.00" + cell.SetStyle(style); + + // Save the workbook to a temporary file + string filePath = "CultureValidation.xlsx"; + workbook.Save(filePath, SaveFormat.Xlsx); + + // -------------------- Load workbook with culture -------------------- + LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx); + loadOptions.CultureInfo = germanCulture; // Ensure the same culture is used during load + + Workbook loadedWorkbook = new Workbook(filePath, loadOptions); + Cell loadedCell = loadedWorkbook.Worksheets[0].Cells["A1"]; + + // Retrieve the formatted string value after loading + string loadedStringValue = loadedCell.StringValue; + + // Expected formatted string according to German culture + string expectedStringValue = numericValue.ToString("N2", germanCulture); // "1.234,56" + + // -------------------- Validation -------------------- + Console.WriteLine($"Loaded string value : \"{loadedStringValue}\""); + Console.WriteLine($"Expected string value: \"{expectedStringValue}\""); + + if (loadedStringValue == expectedStringValue) + { + Console.WriteLine("Success: Number formatting respects the loaded CultureInfo."); + } + else + { + Console.WriteLine("Failure: Number formatting does NOT respect the loaded CultureInfo."); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/verify-that-chart-titles-and-axis-labels-display-localized-text-when-source-cells-contain-localized-strings.cs b/globalization-and-localization/verify-that-chart-titles-and-axis-labels-display-localized-text-when-source-cells-contain-localized-strings.cs new file mode 100644 index 0000000000..2c5b60894a --- /dev/null +++ b/globalization-and-localization/verify-that-chart-titles-and-axis-labels-display-localized-text-when-source-cells-contain-localized-strings.cs @@ -0,0 +1,49 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +class VerifyChartLocalization +{ + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet worksheet = workbook.Worksheets[0]; + + // ----- Localized source data ----- + // Japanese strings for categories, values, and labels + worksheet.Cells["A1"].PutValue("カテゴリ"); // Header for categories + worksheet.Cells["A2"].PutValue("商品A"); // Category 1 + worksheet.Cells["A3"].PutValue("商品B"); // Category 2 + worksheet.Cells["B1"].PutValue("売上"); // Header for values + worksheet.Cells["B2"].PutValue(120); // Value 1 + worksheet.Cells["B3"].PutValue(150); // Value 2 + + // Cells that contain the localized chart title and axis titles + worksheet.Cells["C1"].PutValue("売上チャート"); // Chart title + worksheet.Cells["D1"].PutValue("商品"); // Category (X) axis title + worksheet.Cells["E1"].PutValue("金額 (千円)"); // Value (Y) axis title + + // ----- Create a chart ----- + // Add a column chart positioned from row 5, column 0 to row 20, column 10 + int chartIndex = worksheet.Charts.Add(ChartType.Column, 5, 0, 20, 10); + Chart chart = worksheet.Charts[chartIndex]; + + // Bind data series and categories + chart.NSeries.Add("B2:B3", true); // Values + chart.NSeries.CategoryData = "A2:A3"; // Categories + + // ----- Apply localized titles from source cells ----- + chart.Title.Text = worksheet.Cells["C1"].StringValue; // Chart title + chart.CategoryAxis.Title.Text = worksheet.Cells["D1"].StringValue; // X‑axis title + chart.ValueAxis.Title.Text = worksheet.Cells["E1"].StringValue; // Y‑axis title + + // ----- Verification output ----- + Console.WriteLine("Chart Title: " + chart.Title.Text); + Console.WriteLine("Category Axis Title: " + chart.CategoryAxis.Title.Text); + Console.WriteLine("Value Axis Title: " + chart.ValueAxis.Title.Text); + + // Save the workbook (lifecycle rule) + workbook.Save("LocalizedChart.xlsx"); + } +} \ No newline at end of file diff --git a/globalization-and-localization/verify-that-localized-function-names-are-correctly-recognized-by-excel-when-the-workbook-is-opened.cs b/globalization-and-localization/verify-that-localized-function-names-are-correctly-recognized-by-excel-when-the-workbook-is-opened.cs new file mode 100644 index 0000000000..da6de332e8 --- /dev/null +++ b/globalization-and-localization/verify-that-localized-function-names-are-correctly-recognized-by-excel-when-the-workbook-is-opened.cs @@ -0,0 +1,47 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsLocalizationDemo +{ + class Program + { + static void Main() + { + // Create a new workbook and get the first worksheet + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Create customizable globalization settings + SettableGlobalizationSettings settings = new SettableGlobalizationSettings(); + + // Map the standard English function name "SUM" to the French localized name "SOMME" + // bidirectional = true enables automatic reverse mapping (local -> standard) + settings.SetLocalFunctionName("SUM", "SOMME", true); + + // Apply the custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = settings; + + // Verify the mapping by retrieving the localized name for "SUM" + string localizedName = settings.GetLocalFunctionName("SUM"); + Console.WriteLine($"Localized name for 'SUM' is: {localizedName}"); + + // Populate sample data in column B (B1:B5) + for (int i = 0; i < 5; i++) + { + sheet.Cells[$"B{i + 1}"].PutValue(i + 1); // Values 1,2,3,4,5 + } + + // Use the localized function name in a formula + sheet.Cells["A1"].Formula = $"={localizedName}(B1:B5)"; + + // Calculate all formulas in the workbook + workbook.CalculateFormula(); + + // Output the calculation result + Console.WriteLine($"Result of formula in A1 ({sheet.Cells["A1"].Formula}): {sheet.Cells["A1"].Value}"); + + // Save the workbook – when opened in Excel (with French locale) the formula will appear as =SOMME(...) + workbook.Save("LocalizedFunctionDemo.xlsx"); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-a-script-that-extracts-chart-images-applies-a-localized-other-label-and-saves-them-as-pdf-pages.cs b/globalization-and-localization/write-a-script-that-extracts-chart-images-applies-a-localized-other-label-and-saves-them-as-pdf-pages.cs new file mode 100644 index 0000000000..69f3558392 --- /dev/null +++ b/globalization-and-localization/write-a-script-that-extracts-chart-images-applies-a-localized-other-label-and-saves-them-as-pdf-pages.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Drawing; +using Aspose.Cells.Rendering; + +namespace AsposeCellsChartExport +{ + class Program + { + static void Main() + { + // Load the source workbook that contains charts + string sourcePath = "SourceWorkbook.xlsx"; + Workbook workbook = new Workbook(sourcePath); + + // Iterate through all worksheets + for (int wsIndex = 0; wsIndex < workbook.Worksheets.Count; wsIndex++) + { + Worksheet sheet = workbook.Worksheets[wsIndex]; + + // Iterate through all charts in the current worksheet + for (int chartIndex = 0; chartIndex < sheet.Charts.Count; chartIndex++) + { + Chart chart = sheet.Charts[chartIndex]; + + // Apply a localized label – here we set the chart title to the word "Other" + // In a real scenario you could replace specific category names instead. + chart.Title.Text = "Other"; + + // ---------- Export chart as an image (PNG) ---------- + string imageFile = $"Chart_{wsIndex}_{chartIndex}.png"; + chart.ToImage(imageFile, ImageType.Png); + + // ---------- Export chart as a PDF page ---------- + // Define PDF page size (8.5 x 11 inches) and center alignment + string pdfFile = $"Chart_{wsIndex}_{chartIndex}.pdf"; + chart.ToPdf(pdfFile, 8.5f, 11f, + PageLayoutAlignmentType.Center, + PageLayoutAlignmentType.Center); + + Console.WriteLine($"Chart {chartIndex} on worksheet {wsIndex} exported to image and PDF."); + } + } + + // Optionally, save the modified workbook (titles changed) back to disk + string modifiedWorkbook = "SourceWorkbook_Modified.xlsx"; + workbook.Save(modifiedWorkbook); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-a-script-that-extracts-the-other-label-text-from-rendered-pie-charts-for-localization-quality-checks.cs b/globalization-and-localization/write-a-script-that-extracts-the-other-label-text-from-rendered-pie-charts-for-localization-quality-checks.cs new file mode 100644 index 0000000000..82d9bc30df --- /dev/null +++ b/globalization-and-localization/write-a-script-that-extracts-the-other-label-text-from-rendered-pie-charts-for-localization-quality-checks.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Cells; +using Aspose.Cells.Charts; +using Aspose.Cells.Settings; // Namespace for ChartGlobalizationSettings + +namespace AsposeCellsExamples +{ + public class ExtractOtherLabelFromPieChart + { + public static void Run() + { + try + { + // Create a new workbook (lifecycle: create) + Workbook workbook = new Workbook(); + Worksheet sheet = workbook.Worksheets[0]; + + // Populate sample data for a pie chart + sheet.Cells["A1"].PutValue("Category"); + sheet.Cells["A2"].PutValue("A"); + sheet.Cells["A3"].PutValue("B"); + sheet.Cells["A4"].PutValue("C"); + sheet.Cells["A5"].PutValue("Other"); // Category that will be rendered as "Other" + + sheet.Cells["B1"].PutValue("Value"); + sheet.Cells["B2"].PutValue(30); + sheet.Cells["B3"].PutValue(45); + sheet.Cells["B4"].PutValue(15); + sheet.Cells["B5"].PutValue(10); // Small slice that may be grouped as "Other" depending on chart settings + + // Add a pie chart + int chartIndex = sheet.Charts.Add(ChartType.Pie, 7, 0, 25, 10); + Chart chart = sheet.Charts[chartIndex]; + chart.NSeries.Add("B2:B5", true); // Values + chart.NSeries.CategoryData = "A2:A5"; // Categories + + // Force chart calculation to render labels + chart.Calculate(); + + // Retrieve the default "Other" label text using globalization settings + ChartGlobalizationSettings globalization = new ChartGlobalizationSettings(); + string otherLabel = globalization.GetOtherName(); + + // Output the retrieved label + Console.WriteLine("Default 'Other' label text: " + otherLabel); + + // Save the workbook (lifecycle: save) + string outputPath = "OtherLabelExtraction.xlsx"; + workbook.Save(outputPath); + Console.WriteLine($"Workbook saved to '{Path.GetFullPath(outputPath)}'."); + } + catch (Exception ex) + { + Console.WriteLine("An error occurred: " + ex.Message); + } + } + } + + // Entry point for the application + public class Program + { + public static void Main(string[] args) + { + ExtractOtherLabelFromPieChart.Run(); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-code-to-export-a-workbooks-chart-objects-to-separate-pdf-files-each-preserving-custom-globalization-settings.cs b/globalization-and-localization/write-code-to-export-a-workbooks-chart-objects-to-separate-pdf-files-each-preserving-custom-globalization-settings.cs new file mode 100644 index 0000000000..f54e7029db --- /dev/null +++ b/globalization-and-localization/write-code-to-export-a-workbooks-chart-objects-to-separate-pdf-files-each-preserving-custom-globalization-settings.cs @@ -0,0 +1,63 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Charts; + +namespace ExportChartsToPdf +{ + // Custom globalization settings for charts + public class CustomChartGlobalizationSettings : ChartGlobalizationSettings + { + // Example: customize axis unit names + public override string GetAxisUnitName(DisplayUnitType type) + { + switch (type) + { + case DisplayUnitType.Hundreds: + return "Hundreds_Custom"; + case DisplayUnitType.Thousands: + return "Thousands_Custom"; + case DisplayUnitType.TenThousands: + return "TenThousands_Custom"; + default: + return base.GetAxisUnitName(type); + } + } + + // Additional overrides can be added as needed + } + + public class Program + { + public static void Main() + { + // Load an existing workbook (replace with your file path) + Workbook workbook = new Workbook("input.xlsx"); + + // Apply custom globalization settings to the workbook + workbook.Settings.GlobalizationSettings = new GlobalizationSettings + { + ChartSettings = new CustomChartGlobalizationSettings() + }; + + // Iterate through all worksheets + for (int wsIndex = 0; wsIndex < workbook.Worksheets.Count; wsIndex++) + { + Worksheet sheet = workbook.Worksheets[wsIndex]; + + // Iterate through all charts in the current worksheet + for (int chartIndex = 0; chartIndex < sheet.Charts.Count; chartIndex++) + { + Chart chart = sheet.Charts[chartIndex]; + + // Build a unique PDF file name for each chart + string pdfFileName = $"Chart_Sheet{wsIndex + 1}_Chart{chartIndex + 1}.pdf"; + + // Export the chart to PDF while preserving the custom globalization settings + chart.ToPdf(pdfFileName); + } + } + + Console.WriteLine("All charts have been exported to separate PDF files."); + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-unit-tests-asserting-getlocalfunctionname-returns-expected-localized-equivalents-for-common-functions.cs b/globalization-and-localization/write-unit-tests-asserting-getlocalfunctionname-returns-expected-localized-equivalents-for-common-functions.cs new file mode 100644 index 0000000000..e72e5dbe65 --- /dev/null +++ b/globalization-and-localization/write-unit-tests-asserting-getlocalfunctionname-returns-expected-localized-equivalents-for-common-functions.cs @@ -0,0 +1,101 @@ +using System; +using Aspose.Cells; +using Aspose.Cells.Settings; + +namespace AsposeCellsTests +{ + class Program + { + static void Main() + { + RunTest(() => GetLocalFunctionName_ShouldReturnMappedName_ForSum(), + nameof(GetLocalFunctionName_ShouldReturnMappedName_ForSum)); + RunTest(() => GetLocalFunctionName_ShouldReturnMappedName_ForAverage(), + nameof(GetLocalFunctionName_ShouldReturnMappedName_ForAverage)); + RunTest(() => GetLocalFunctionName_ShouldReturnMappedName_ForMax(), + nameof(GetLocalFunctionName_ShouldReturnMappedName_ForMax)); + RunTest(() => GetLocalFunctionName_ShouldReturnStandardName_WhenNoMappingExists(), + nameof(GetLocalFunctionName_ShouldReturnStandardName_WhenNoMappingExists)); + RunTest(() => GetLocalFunctionName_ShouldBeCaseInsensitive_ForStandardName(), + nameof(GetLocalFunctionName_ShouldBeCaseInsensitive_ForStandardName)); + } + + // Executes a test method and reports the result. + static void RunTest(Action testMethod, string testName) + { + try + { + testMethod(); + Console.WriteLine($"{testName}: Passed"); + } + catch (Exception ex) + { + Console.WriteLine($"{testName}: Failed - {ex.Message}"); + } + } + + // Helper to create a workbook with custom SettableGlobalizationSettings. + private static Workbook CreateWorkbook(out SettableGlobalizationSettings settings) + { + var workbook = new Workbook(); + settings = new SettableGlobalizationSettings(); + workbook.Settings.GlobalizationSettings = settings; + return workbook; + } + + private static void GetLocalFunctionName_ShouldReturnMappedName_ForSum() + { + var workbook = CreateWorkbook(out var settings); + settings.SetLocalFunctionName("SUM", "SOMME", true); + string localName = settings.GetLocalFunctionName("SUM"); + Assert.AreEqual("SOMME", localName, "The localized name for SUM should be SOMME."); + } + + private static void GetLocalFunctionName_ShouldReturnMappedName_ForAverage() + { + var workbook = CreateWorkbook(out var settings); + settings.SetLocalFunctionName("AVERAGE", "MITTELWERT", true); + string localName = settings.GetLocalFunctionName("AVERAGE"); + Assert.AreEqual("MITTELWERT", localName, "The localized name for AVERAGE should be MITTELWERT."); + } + + private static void GetLocalFunctionName_ShouldReturnMappedName_ForMax() + { + var workbook = CreateWorkbook(out var settings); + settings.SetLocalFunctionName("MAX", "MASSIMO", true); + string localName = settings.GetLocalFunctionName("MAX"); + Assert.AreEqual("MASSIMO", localName, "The localized name for MAX should be MASSIMO."); + } + + private static void GetLocalFunctionName_ShouldReturnStandardName_WhenNoMappingExists() + { + var workbook = CreateWorkbook(out var settings); + string localName = settings.GetLocalFunctionName("MIN"); + Assert.AreEqual("MIN", localName, "Without a mapping, GetLocalFunctionName should return the standard name."); + } + + private static void GetLocalFunctionName_ShouldBeCaseInsensitive_ForStandardName() + { + var workbook = CreateWorkbook(out var settings); + settings.SetLocalFunctionName("SUM", "SUMA", true); + string localNameUpper = settings.GetLocalFunctionName("SUM"); + string localNameLower = settings.GetLocalFunctionName("sum"); + string localNameMixed = settings.GetLocalFunctionName("SuM"); + Assert.AreEqual("SUMA", localNameUpper); + Assert.AreEqual("SUMA", localNameLower); + Assert.AreEqual("SUMA", localNameMixed); + } + + // Minimal assertion helper to replace NUnit. + static class Assert + { + public static void AreEqual(string expected, string actual, string message = null) + { + if (!string.Equals(expected, actual, StringComparison.Ordinal)) + { + throw new Exception(message ?? $"Expected '{expected}', but got '{actual}'."); + } + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-unit-tests-for-getbooleanstring-covering-true-false-and-null-values-in-different-locales.cs b/globalization-and-localization/write-unit-tests-for-getbooleanstring-covering-true-false-and-null-values-in-different-locales.cs new file mode 100644 index 0000000000..db0ee5ca9d --- /dev/null +++ b/globalization-and-localization/write-unit-tests-for-getbooleanstring-covering-true-false-and-null-values-in-different-locales.cs @@ -0,0 +1,133 @@ +using System; +using Aspose.Cells; + +namespace AsposeCellsTests +{ + // Custom globalization settings that return locale‑specific boolean strings. + public class RussianBooleanGlobalizationSettings : GlobalizationSettings + { + public override string GetBooleanValueString(bool bv) + { + // Russian words for true/false. + return bv ? "ИСТИНА" : "ЛОЖЬ"; + } + } + + public static class SimpleAssert + { + public static void AreEqual(string expected, string actual, string message) + { + if (!string.Equals(expected, actual, StringComparison.Ordinal)) + throw new Exception($"Assert Failed: {message} Expected='{expected}', Actual='{actual}'."); + } + } + + public class GetBooleanValueStringTests + { + // Test the default implementation (no custom settings). + public void Default_GetBooleanValueString_ReturnsEnglishStrings() + { + // Arrange + Workbook workbook = new Workbook(); // default workbook + GlobalizationSettings settings = workbook.Settings.GlobalizationSettings; + + // Act + string trueStr = settings.GetBooleanValueString(true); + string falseStr = settings.GetBooleanValueString(false); + + // Assert + SimpleAssert.AreEqual("TRUE", trueStr, "Default true string should be 'TRUE'."); + SimpleAssert.AreEqual("FALSE", falseStr, "Default false string should be 'FALSE'."); + } + + // Test custom strings set via SettableGlobalizationSettings. + public void SettableGlobalizationSettings_CustomBooleanStrings_AreReturned() + { + // Arrange + Workbook workbook = new Workbook(); + var customSettings = new SettableGlobalizationSettings(); + customSettings.SetBooleanValueString(true, "YES_CUSTOM"); + customSettings.SetBooleanValueString(false, "NO_CUSTOM"); + workbook.Settings.GlobalizationSettings = customSettings; + + // Act + string trueStr = customSettings.GetBooleanValueString(true); + string falseStr = customSettings.GetBooleanValueString(false); + + // Assert + SimpleAssert.AreEqual("YES_CUSTOM", trueStr, "Custom true string should match the value set."); + SimpleAssert.AreEqual("NO_CUSTOM", falseStr, "Custom false string should match the value set."); + } + + // Test a locale‑specific override (e.g., Russian) using a derived GlobalizationSettings class. + public void CustomGlobalizationSettings_RussianLocale_ReturnsRussianStrings() + { + // Arrange + Workbook workbook = new Workbook(); + workbook.Settings.GlobalizationSettings = new RussianBooleanGlobalizationSettings(); + + // Act + string trueStr = workbook.Settings.GlobalizationSettings.GetBooleanValueString(true); + string falseStr = workbook.Settings.GlobalizationSettings.GetBooleanValueString(false); + + // Assert + SimpleAssert.AreEqual("ИСТИНА", trueStr, "Russian true string should be 'ИСТИНА'."); + SimpleAssert.AreEqual("ЛОЖЬ", falseStr, "Russian false string should be 'ЛОЖЬ'."); + } + + // Test behavior when GlobalizationSettings is null (should fallback to default). + public void Null_GlobalizationSettings_UsesDefaultImplementation() + { + // Arrange + Workbook workbook = new Workbook(); + // Explicitly set to null to simulate missing settings. + workbook.Settings.GlobalizationSettings = null; + + // Act + // Accessing the property returns the default GlobalizationSettings instance. + GlobalizationSettings settings = workbook.Settings.GlobalizationSettings; + string trueStr = settings.GetBooleanValueString(true); + string falseStr = settings.GetBooleanValueString(false); + + // Assert + SimpleAssert.AreEqual("TRUE", trueStr, "When settings are null, true should map to 'TRUE'."); + SimpleAssert.AreEqual("FALSE", falseStr, "When settings are null, false should map to 'FALSE'."); + } + } + + class Program + { + static void Main() + { + var tests = new GetBooleanValueStringTests(); + + RunTest(() => tests.Default_GetBooleanValueString_ReturnsEnglishStrings(), + nameof(tests.Default_GetBooleanValueString_ReturnsEnglishStrings)); + + RunTest(() => tests.SettableGlobalizationSettings_CustomBooleanStrings_AreReturned(), + nameof(tests.SettableGlobalizationSettings_CustomBooleanStrings_AreReturned)); + + RunTest(() => tests.CustomGlobalizationSettings_RussianLocale_ReturnsRussianStrings(), + nameof(tests.CustomGlobalizationSettings_RussianLocale_ReturnsRussianStrings)); + + RunTest(() => tests.Null_GlobalizationSettings_UsesDefaultImplementation(), + nameof(tests.Null_GlobalizationSettings_UsesDefaultImplementation)); + + Console.WriteLine("All tests completed."); + } + + // Executes a test method inside a try‑catch block and reports the result. + private static void RunTest(Action testMethod, string testName) + { + try + { + testMethod(); + Console.WriteLine($"{testName}: Passed"); + } + catch (Exception ex) + { + Console.WriteLine($"{testName}: Failed - {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/globalization-and-localization/write-unit-tests-for-geterrorstring-covering-standard-excel-error-codes-across-multiple-locales.cs b/globalization-and-localization/write-unit-tests-for-geterrorstring-covering-standard-excel-error-codes-across-multiple-locales.cs new file mode 100644 index 0000000000..52ac6fb596 --- /dev/null +++ b/globalization-and-localization/write-unit-tests-for-geterrorstring-covering-standard-excel-error-codes-across-multiple-locales.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using Aspose.Cells; + +namespace AsposeCellsTests +{ + // Custom globalization settings that map standard error codes to localized strings + public class CustomErrorGlobalizationSettings : SettableGlobalizationSettings + { + private readonly Dictionary _errorMap = new Dictionary + { + { "#DIV/0!", "Division by zero" }, + { "#VALUE!", "Invalid value" }, + { "#NAME?", "Invalid name" }, + { "#N/A", "Not available" }, + { "#REF!", "Invalid reference" }, + { "#NUM!", "Invalid number" }, + { "#NULL!", "Intersection error" }, + { "#SPILL!", "Spill error" }, + { "#BUSY!", "Busy error" }, + { "#CALC!", "Calculation error" } + }; + + public override string GetErrorValueString(string err) + { + // Return the localized string if a mapping exists; otherwise fall back to default behavior + return _errorMap.TryGetValue(err, out var localized) ? localized : base.GetErrorValueString(err); + } + } + + public static class Program + { + private static SettableGlobalizationSettings _settings; + + public static void Main() + { + try + { + Setup(); + RunAllTests(); + Console.WriteLine("All tests passed."); + } + catch (Exception ex) + { + Console.WriteLine($"Test failed: {ex.Message}"); + } + } + + // Create a workbook and assign the custom globalization settings + private static void Setup() + { + try + { + var workbook = new Workbook(); + _settings = new CustomErrorGlobalizationSettings(); + workbook.Settings.GlobalizationSettings = _settings; + } + catch (Exception ex) + { + throw new InvalidOperationException("Failed to set up workbook with custom globalization settings.", ex); + } + } + + // Execute each test case manually + private static void RunAllTests() + { + // Standard error codes and their expected localized strings + var testCases = new Dictionary + { + { "#DIV/0!", "Division by zero" }, + { "#VALUE!", "Invalid value" }, + { "#NAME?", "Invalid name" }, + { "#N/A", "Not available" }, + { "#REF!", "Invalid reference" }, + { "#NUM!", "Invalid number" }, + { "#NULL!", "Intersection error" }, + { "#SPILL!", "Spill error" }, + { "#BUSY!", "Busy error" }, + { "#CALC!", "Calculation error" } + }; + + foreach (var kvp in testCases) + { + VerifyLocalizedString(kvp.Key, kvp.Value); + } + + VerifyUnknownError(); + } + + // Verify that a known error code returns the expected localized string + private static void VerifyLocalizedString(string errorCode, string expectedLocalized) + { + try + { + string actual = _settings.GetErrorValueString(errorCode); + if (!string.Equals(actual, expectedLocalized, StringComparison.Ordinal)) + { + throw new Exception($"Error code '{errorCode}' expected '{expectedLocalized}' but got '{actual}'."); + } + } + catch (Exception ex) + { + throw new Exception($"Verification failed for error code '{errorCode}'.", ex); + } + } + + // Verify that an unknown error code is returned unchanged (default behavior) + private static void VerifyUnknownError() + { + const string unknownError = "#UNKNOWN!"; + try + { + string result = _settings.GetErrorValueString(unknownError); + if (!string.Equals(result, unknownError, StringComparison.Ordinal)) + { + throw new Exception($"Unknown error code expected to be unchanged but got '{result}'."); + } + } + catch (Exception ex) + { + throw new Exception("Verification failed for unknown error code.", ex); + } + } + } +} \ No newline at end of file diff --git a/index.json b/index.json index e6b002cd9b..6ca481c0ac 100644 --- a/index.json +++ b/index.json @@ -3559,6 +3559,61 @@ "file": "create-a-configuration-file-mapping-locale-identifiers-to-corresponding-custom-globalizationsettings-classes.cs", "title": "Create a configuration file mapping locale identifiers to corresponding custom GlobalizationSettings classes." }, + { + "category": "globalization-and-localization", + "file": "add-subtotal-rows-to-the-worksheet-after-assigning-custom-globalizationsettings-verifying-localized-total-labels.cs", + "title": "Add subtotal rows to the worksheet after assigning custom GlobalizationSettings, verifying localized total labels." + }, + { + "category": "globalization-and-localization", + "file": "apply-custom-number-format-strings-to-percentage-cells-after-loading-the-workbook-with-brazilian-portuguese-cultureinfo.cs", + "title": "Apply custom number format strings to percentage cells after loading the workbook with Brazilian Portuguese CultureInfo." + }, + { + "category": "globalization-and-localization", + "file": "assign-the-custom-globalizationsettings-instance-to-workbooksettingsglobalizationsettings-before-loading-any-worksheets.cs", + "title": "Assign the custom GlobalizationSettings instance to Workbook.Settings.GlobalizationSettings before loading any worksheets." + }, + { + "category": "globalization-and-localization", + "file": "assign-the-custom-globalizationsettings-to-the-workbook-before-adding-subtotals-to-ensure-localized-labels.cs", + "title": "Assign the custom GlobalizationSettings to the workbook before adding subtotals to ensure localized labels." + }, + { + "category": "globalization-and-localization", + "file": "batch-process-a-folder-of-xlsx-files-loading-each-with-spanish-cultureinfo-and-exporting-charts-to-png-images.cs", + "title": "Batch process a folder of XLSX files, loading each with Spanish CultureInfo and exporting charts to PNG images." + }, + { + "category": "globalization-and-localization", + "file": "compare-pdf-output-of-a-workbook-loaded-with-invariant-culture-versus-french-culture-to-assess-number-format-differences.cs", + "title": "Compare PDF output of a workbook loaded with invariant culture versus French culture to assess number format differences." + }, + { + "category": "globalization-and-localization", + "file": "configure-chart-rendering-to-use-antialiasing-while-applying-custom-chartglobalizationsettings-for-improved-visual-quality.cs", + "title": "Configure chart rendering to use anti\u2011aliasing while applying custom ChartGlobalizationSettings for improved visual quality." + }, + { + "category": "globalization-and-localization", + "file": "configure-workbook-to-use-a-specific-cultureinfo-object-for-date-and-number-formats-during-localization.cs", + "title": "Configure workbook to use a specific CultureInfo object for date and number formats during localization." + }, + { + "category": "globalization-and-localization", + "file": "convert-gregorian-date-cells-to-japanese-calendar-dates-with-cellshelper-preserving-era-information-for-each-cell.cs", + "title": "Convert Gregorian date cells to Japanese calendar dates with CellsHelper, preserving era information for each cell." + }, + { + "category": "globalization-and-localization", + "file": "create-a-batch-process-that-applies-the-custom-globalization-settings-to-all-workbooks-in-a-folder.cs", + "title": "Create a batch process that applies the custom globalization settings to all workbooks in a folder." + }, + { + "category": "globalization-and-localization", + "file": "create-a-configuration-file-mapping-locale-identifiers-to-corresponding-custom-globalizationsettings-classes.cs", + "title": "Create a configuration file mapping locale identifiers to corresponding custom GlobalizationSettings classes." + }, { "category": "globalization-and-localization", "file": "create-a-custom-globalizationsettings-class-overriding-getlocalfunctionname-for-target-language-functions.cs",