Aspose.Cells JSON Converter for .NET

Aspose.Cells JSON Converter for .NET provides seamless, high-performance conversion between Microsoft Excel workbooks (XLS, XLSX, XLSM) and JSON data structures. Whether you need to serialize worksheet contents into JSON for web apps or reconstruct Excel files from JSON payloads, this plugin ensures accuracy, schema validation, and efficient performance.

Installation and Setup

  1. Install the NuGet package: see Installation .
  2. Configure metered licensing before using APIs: see Metered Licensing .

With licensing enabled and package installed, you can immediately integrate JSON conversion workflows into your .NET applications.

Key Features

Format Coverage

  • Supports XLS, XLSX, XLSM, XLTX, XLTM, XLSB.
  • Retains formulas, styles, merged regions, and workbook metadata.
  • Ensures round-trip conversions from Excel to JSON and back.

Custom JSON Schema Mapping

  • Map ranges to JSON arrays or objects.
  • Include/exclude headers, hidden rows, and footers.
  • Control formatting for numbers, dates, and booleans.
  • Match JSON outputs with REST API contracts or existing schemas.

Stream-Based Processing

  • Memory Stream Support: Convert directly to memory streams for in-memory processing.
  • Efficient I/O: Process large datasets using streaming read/write.
  • Web Integration: Output JSON directly to HTTP response streams in web applications.
  • Zero File System Access: Complete conversions without touching disk storage.

Performance and Streaming

  • Convert row-by-row or in batches without loading entire workbook.
  • Supports async I/O for non-blocking operations in ASP.NET Core.
  • Minimizes memory footprint for large-scale conversions.

Advanced Options

  • Custom cell value transformers (e.g., date serializers).
  • Control JSON indentation, encoding, and null policies.
  • Preserve leading zeros, special characters, and locale-specific formats.

Output Validation and Quality Assurance

  • Content Verification: Validate JSON output contains expected data.
  • Programmatic Testing: Search and verify specific values in generated JSON.
  • Data Integrity Checks: Ensure critical fields are present in output.

Error Handling and Validation

  • Detect invalid formulas, corrupt streams, or schema mismatches.
  • Validation callbacks for handling or correcting errors.
  • Clear exception hierarchy for debugging and troubleshooting.

Usage Examples

Basic Conversion: Excel to JSON

The simplest way to convert an Excel file to JSON using a single line of code:

using Aspose.Cells.LowCode;

string src = "mytemplate.xlsx";
JsonConverter.Process(src, "result\\PluginJson1.json");

This converts the entire workbook to a JSON file with default settings.

Advanced Conversion with Stream-Based Output

Process conversions entirely in memory without file system access:

using Aspose.Cells.LowCode;
using System.IO;
using System.Text;

string src = "mytemplate.xlsx";

// Configure load options
LowCodeLoadOptions lclopts = new LowCodeLoadOptions();
lclopts.InputFile = src;

// Configure save options
LowCodeSaveOptions lcsopts = new LowCodeSaveOptions();

// Output to memory stream for in-memory processing
MemoryStream ms = new MemoryStream();
lcsopts.OutputStream = ms;

// Perform conversion
JsonConverter.Process(lclopts, lcsopts);

// Validate output contains expected data
string jsonContent = Encoding.ASCII.GetString(ms.ToArray());
Console.WriteLine(jsonContent.IndexOf("Column1") > 0 
    ? "Found the first cell value" 
    : "Cannot find the expected cell value");

Feature Breakdown: Stream-Based Output

Convert to memory streams for flexible processing and integration:

// Create memory stream for output
MemoryStream ms = new MemoryStream();
lcsopts.OutputStream = ms;

// Perform conversion
JsonConverter.Process(lclopts, lcsopts);

// Access the JSON as byte array
byte[] jsonBytes = ms.ToArray();

// Access the JSON as string
string jsonString = Encoding.UTF8.GetString(jsonBytes);

// Use in web API
return Content(jsonString, "application/json");

Use Cases:

  • REST API endpoints returning Excel data as JSON
  • Cloud functions with ephemeral storage
  • Microservices processing data in-memory
  • Caching JSON representations in Redis or memory cache
  • Real-time data feeds from Excel templates
  • Testing and validation without file I/O

Feature Breakdown: Output Validation

Verify that converted JSON contains expected data:

string jsonContent = Encoding.UTF8.GetString(ms.ToArray());

// Check for specific column headers
bool hasColumn1 = jsonContent.IndexOf("Column1") > 0;
bool hasColumn2 = jsonContent.IndexOf("Column2") > 0;

// Validate data presence
if (hasColumn1 && hasColumn2)
{
    Console.WriteLine("All expected columns found in JSON output");
}
else
{
    Console.WriteLine("Warning: Missing expected columns");
}

// Parse and validate JSON structure
try
{
    var jsonDoc = System.Text.Json.JsonDocument.Parse(jsonContent);
    Console.WriteLine("JSON is valid and well-formed");
}
catch (System.Text.Json.JsonException ex)
{
    Console.WriteLine($"Invalid JSON: {ex.Message}");
}

Validation Strategies:

  • Content Search: Use IndexOf() to find specific field names or values
  • JSON Parsing: Parse output to verify structure validity
  • Schema Validation: Compare against expected JSON schema
  • Data Type Checks: Ensure numbers, dates, and booleans are correctly formatted
  • Completeness Tests: Verify all expected rows/columns are present

Feature Breakdown: LowCode API Benefits

The LowCode API provides simplified, streamlined conversion:

// Traditional API (verbose)
Workbook workbook = new Workbook("sample.xlsx");
workbook.Save("output.json", SaveFormat.Json);

// LowCode API (concise)
JsonConverter.Process("sample.xlsx", "output.json");

LowCode Advantages:

  • Fewer lines of code
  • Reduced memory footprint
  • Faster execution
  • Cleaner syntax
  • Built-in best practices

Traditional API: Fine-Grained Control

For scenarios requiring maximum customization, use the traditional Workbook API:

using Aspose.Cells;

// Load your source workbook
Workbook workbook = new Workbook("sample.xlsx");

// Configure JSON save options
JsonSaveOptions saveOptions = new JsonSaveOptions();
saveOptions.ExportArea = new CellArea 
{ 
    StartRow = 0, 
    StartColumn = 0, 
    EndRow = 10, 
    EndColumn = 5 
};
saveOptions.ExportAsString = true;
saveOptions.Indent = "  ";  // Pretty-print with 2-space indentation

// Convert the workbook to JSON file
workbook.Save("sample_out.json", saveOptions);

Web API Integration Example

Use stream-based conversion in ASP.NET Core controllers:

[HttpGet("export-to-json")]
public IActionResult ExportToJson(string filename)
{
    try
    {
        LowCodeLoadOptions loadOpts = new LowCodeLoadOptions();
        loadOpts.InputFile = filename;

        LowCodeSaveOptions saveOpts = new LowCodeSaveOptions();
        MemoryStream ms = new MemoryStream();
        saveOpts.OutputStream = ms;

        JsonConverter.Process(loadOpts, saveOpts);

        string jsonContent = Encoding.UTF8.GetString(ms.ToArray());
        return Content(jsonContent, "application/json");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Conversion error: {ex.Message}");
    }
}

Batch Processing with Validation

Process multiple files with output validation:

string[] excelFiles = Directory.GetFiles("input", "*.xlsx");

foreach (string file in excelFiles)
{
    try
    {
        LowCodeLoadOptions loadOpts = new LowCodeLoadOptions();
        loadOpts.InputFile = file;

        LowCodeSaveOptions saveOpts = new LowCodeSaveOptions();
        MemoryStream ms = new MemoryStream();
        saveOpts.OutputStream = ms;

        JsonConverter.Process(loadOpts, saveOpts);

        string json = Encoding.UTF8.GetString(ms.ToArray());
        
        // Validate JSON before saving
        if (json.Length > 0 && json.Contains("{"))
        {
            string outputFile = Path.Combine("output", 
                Path.GetFileNameWithoutExtension(file) + ".json");
            File.WriteAllText(outputFile, json);
            Console.WriteLine($"✓ Converted: {Path.GetFileName(file)}");
        }
        else
        {
            Console.WriteLine($"✗ Invalid output: {Path.GetFileName(file)}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"✗ Error processing {file}: {ex.Message}");
    }
}

Tips and Best Practices

Performance Optimization

  • Use LowCode API: Leverage JsonConverter.Process() for faster conversions with less overhead.
  • Stream-Based Processing: Use memory streams for in-memory operations to avoid file I/O.
  • Batch Sizes: For large workbooks, enable streaming mode and tune batch sizes.
  • Async Operations: Use async APIs for long-running conversions in web applications.

Data Quality

  • Output Validation: Always validate JSON output using string searches or JSON parsers.
  • Schema Definition: Define JSON schemas once and reuse them across multiple tasks.
  • Transformers: Use custom transformers for consistent formatting of dates and numbers.
  • Input Validation: Validate incoming JSON before importing to Excel.

Memory Management

  • Dispose Streams: Always dispose of memory streams after use to free memory.
  • Stream Reuse: Reset and reuse memory streams for batch conversions.
  • Resource Cleanup: Wrap conversion operations in try-finally blocks for guaranteed cleanup.

Production Deployment

  • Error Handling: Wrap conversion calls in try-catch blocks to handle license and I/O errors.
  • Logging: Log conversion results and validation outcomes for audit trails.
  • Content Verification: Use IndexOf() or JSON parsing to verify critical fields exist.
  • Encoding: Use UTF8 encoding for international character support.

Common Issues and Resolutions

IssueResolution
File not foundVerify the input file path is correct and accessible
Unsupported file formatEnsure the input format is supported (XLS, XLSX, XLSM, etc.)
Expected value not foundCheck column/field names match Excel headers exactly
Empty JSON outputVerify the worksheet contains data and is not hidden
Invalid JSONParse output to identify structural issues
Memory overflowUse streaming mode for very large workbooks
Encoding issuesUse Encoding.UTF8 instead of ASCII for international characters
Stream position errorReset stream position with ms.Seek(0, SeekOrigin.Begin) before reading

Frequently Asked Questions

What is Aspose.Cells JSON Converter for .NET? It enables programmatic conversion of Excel files from/to JSON structures in .NET applications with high performance and accuracy.

How does it differ from Aspose.Cells for .NET? Aspose.Cells is a full-featured library. The JSON Converter focuses on Excel-to-JSON and JSON-to-Excel workflows with streamlined APIs.

Which file formats are supported? XLS, XLSX, XLSM, XLTX, XLTM, XLSB, and JSON.

Can JSON generation be customized? Yes. Use JsonSaveOptions for indentation, encoding, and formatting settings.

Can I convert directly to memory without files? Yes! Use MemoryStream with LowCodeSaveOptions.OutputStream for complete in-memory processing.

How do I validate the JSON output? Use IndexOf() to search for expected values, or parse the JSON with System.Text.Json.JsonDocument to verify structure.

What encoding should I use? Use Encoding.UTF8 for proper support of international characters and special symbols.

Can I use this in web APIs? Absolutely! The stream-based approach is perfect for REST APIs, returning JSON directly from Excel data.


API Reference Summary

Key Classes

  • JsonConverter: Static class providing simplified conversion methods
  • LowCodeLoadOptions: Configuration for loading Excel files
  • LowCodeSaveOptions: Configuration for JSON output
  • JsonSaveOptions: Detailed JSON conversion settings (traditional API)
  • MemoryStream: In-memory stream for zero-file-system conversions

Essential Properties

  • InputFile: Source Excel file path
  • OutputStream: Target stream for JSON output (enables in-memory processing)
  • ExportArea: Specific cell range to export
  • ExportAsString: Export all values as strings
  • Indent: JSON indentation string for pretty-printing

Common Methods

  • JsonConverter.Process(string, string): Simple file-to-file conversion
  • JsonConverter.Process(LowCodeLoadOptions, LowCodeSaveOptions): Advanced conversion with options
  • MemoryStream.ToArray(): Get JSON content as byte array
  • Encoding.UTF8.GetString(byte[]): Convert bytes to JSON string
 English