Aspose.Cells Text Converter for .NET

Aspose.Cells Text Converter for .NET is a high-performance API tailored for converting Microsoft Excel workbooks (XLS, XLSX, XLSM) into multiple text-based formats—including CSV, TSV, XML, and SQLSCRIPT—and vice versa. Built on the robust Aspose.Cells engine, this plugin streamlines text conversion workflows for data-migration tools, reporting pipelines, ETL processes, and spreadsheet processing services.

Installation and Setup

  1. Add the Aspose.Cells NuGet package to your .NET project.
  2. Configure metered licensing to avoid evaluation limitations.

For detailed setup, see the Installation guide. For licensing, follow Metered Licensing .

Features and Functionalities

Comprehensive Format Support

  • Input: XLS, XLSX, XLSM , CSV, TSV, XML, TXT
  • Output: CSV, TSV, XML (customizable), SQLSCRIPT (database-ready INSERT statements), XLSX, XLS
  • Bidirectional Conversion: Convert from Excel to text formats AND from text formats back to Excel
  • Supports round-trip conversions between Excel workbooks and text-based formats

Intelligent Format Detection

  • Automatic Format Inference: Detects input and output formats from file extensions
  • Extension-Based Processing: No need to specify SaveFormat for common conversions
  • Smart Detection: Recognizes .csv, .tsv, .txt, .xlsx, .xls, and more automatically

LowCode API for Simplified Conversion

  • Single-Line Conversions: Convert files with one method call
  • Minimal Configuration: Automatic format detection reduces boilerplate code
  • Optimized Performance: Streamlined execution path for common scenarios
  • Easy Integration: Drop-in replacement for complex conversion logic

Delimiter & Encoding Customization

  • Define custom delimiters, quoting characters, and escape sequences for CSV/TSV
  • Control encoding (UTF-8, UTF-16, ISO-8859-1, etc.) for compatibility
  • Options to include/exclude headers, footers, and blank rows

XML Structure Control

  • Map worksheet data into XML elements and attributes with custom templates
  • Configure root elements, namespaces, and schema-compliant output
  • Supports row-centric and cell-centric XML representations

SQLSCRIPT Generation

  • Convert each row into SQL INSERT statements automatically
  • Customize table names, column lists, and value formatting
  • Batch multiple INSERTs for optimized execution in relational databases

Performance and Scalability

  • Stream-based conversion for large workbooks
  • Parallel conversion using multi-core systems
  • Lightweight for single-sheet exports, high throughput for bulk conversions

Error Handling and Validation

  • Clear exception hierarchy for conversion errors, format violations, and I/O issues
  • Validation hooks to inspect/correct data pre/post conversion
  • Logging integration points for .NET logging frameworks

Usage Examples

Basic Conversion: CSV to Excel (LowCode API)

The simplest way to convert a text file to Excel using automatic format detection:

using Aspose.Cells.LowCode;

// Convert CSV to XLSX (formats inferred from extensions)
TextConverter.Process("data.csv", "output.xlsx");

No need to specify formats—the API automatically detects CSV input and XLSX output based on file extensions.

Basic Conversion: Excel to CSV

Convert Excel files to CSV format just as easily:

using Aspose.Cells.LowCode;

// Convert XLSX to CSV (formats inferred from extensions)
TextConverter.Process("spreadsheet.xlsx", "output.csv");

Complete Example with Metered Licensing

Full application showing licensing setup and conversion:

using Aspose.Cells;
using Aspose.Cells.LowCode;

class ConvertTextToExcel
{
    static void Main()
    {
        // Optional: Configure metered licensing for production use
        // new Metered().SetMeteredKey("PublicKey", "PrivateKey");

        // Convert CSV to XLSX (formats inferred from extensions)
        TextConverter.Process("data.csv", "output.xlsx");
        
        Console.WriteLine("✓ Conversion completed successfully");
    }
}

Feature Breakdown: Automatic Format Detection

The LowCode API intelligently detects formats from file extensions:

// CSV to Excel
TextConverter.Process("input.csv", "output.xlsx");   // Detects CSV → XLSX

// TSV to Excel
TextConverter.Process("input.tsv", "output.xlsx");   // Detects TSV → XLSX

// Excel to CSV
TextConverter.Process("input.xlsx", "output.csv");   // Detects XLSX → CSV

// Excel to TSV
TextConverter.Process("input.xlsx", "output.tsv");   // Detects XLSX → TSV

// TXT to Excel
TextConverter.Process("input.txt", "output.xlsx");   // Detects TXT → XLSX

// Excel to TXT
TextConverter.Process("input.xlsx", "output.txt");   // Detects XLSX → TXT

Supported Extensions:

  • Excel: .xlsx, .xls, .xlsm, .xltx, .xltm, .xlsb
  • Text: .csv, .tsv, .txt
  • XML: .xml
  • Others: Automatically detected based on extension

Feature Breakdown: Bidirectional Conversion

The Text Converter supports conversion in both directions:

Text to Excel:

// Import CSV data into Excel workbook
TextConverter.Process("sales_data.csv", "sales_report.xlsx");

// Import TSV data into Excel
TextConverter.Process("tab_delimited.tsv", "formatted_data.xlsx");

// Import XML into Excel
TextConverter.Process("data_export.xml", "spreadsheet.xlsx");

Excel to Text:

// Export Excel data to CSV
TextConverter.Process("inventory.xlsx", "inventory_export.csv");

// Export Excel to tab-delimited file
TextConverter.Process("report.xlsx", "report_data.tsv");

// Export Excel to plain text
TextConverter.Process("notes.xlsx", "notes.txt");

Use Cases:

  • Data Migration: Move data between Excel and database systems
  • ETL Pipelines: Extract data from Excel for processing
  • Reporting: Convert text logs into Excel for analysis
  • Integration: Exchange data with systems that only support text formats
  • Archival: Convert Excel files to plain text for long-term storage

Feature Breakdown: LowCode vs Traditional API

Compare the simplified LowCode API with the traditional approach:

LowCode API (Recommended for Simple Conversions):

using Aspose.Cells.LowCode;

// One line, automatic format detection
TextConverter.Process("data.csv", "output.xlsx");

Traditional API (For Advanced Customization):

using Aspose.Cells;

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

// Configure CSV options
TxtSaveOptions options = new TxtSaveOptions();
options.Separator = ',';
options.Encoding = System.Text.Encoding.UTF8;
options.QuoteType = TxtValueQuoteType.Always;

// Save with custom options
workbook.Save("output.csv", options);

When to Use Each:

  • LowCode API: Standard conversions, automatic detection needed, minimal code
  • Traditional API: Custom delimiters, encoding control, format-specific options

Advanced: Custom CSV Options with Traditional API

For fine-grained control over CSV output:

using Aspose.Cells;

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

// Configure CSV export options
TxtSaveOptions csvOptions = new TxtSaveOptions(SaveFormat.Csv);
csvOptions.Separator = ';';  // Use semicolon instead of comma
csvOptions.Encoding = System.Text.Encoding.UTF8;
csvOptions.QuoteType = TxtValueQuoteType.Always;
csvOptions.KeepSeparatorsForBlankRow = false;
csvOptions.ExportAllSheets = false;  // Export only active sheet

// Save the workbook to CSV format
workbook.Save("output.csv", csvOptions);

Advanced: TSV Conversion with Options

Export to tab-separated values with custom settings:

using Aspose.Cells;

Workbook workbook = new Workbook("data.xlsx");

TxtSaveOptions tsvOptions = new TxtSaveOptions(SaveFormat.Tsv);
tsvOptions.Separator = '\t';  // Tab character
tsvOptions.Encoding = System.Text.Encoding.UTF8;
tsvOptions.ExportQuotedValue = false;  // Don't quote values

workbook.Save("output.tsv", tsvOptions);

Batch Conversion Example

Convert multiple CSV files to Excel format:

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

string[] csvFiles = Directory.GetFiles("input", "*.csv");

foreach (string csvFile in csvFiles)
{
    try
    {
        string outputFile = Path.Combine("output", 
            Path.GetFileNameWithoutExtension(csvFile) + ".xlsx");
        
        TextConverter.Process(csvFile, outputFile);
        
        Console.WriteLine($"✓ Converted: {Path.GetFileName(csvFile)}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"✗ Error converting {csvFile}: {ex.Message}");
    }
}

Console.WriteLine($"Batch conversion complete. Processed {csvFiles.Length} files.");

ETL Pipeline Integration

Integrate text conversion into data processing workflows:

using Aspose.Cells.LowCode;
using System.Data;

public class DataPipeline
{
    public void ImportCsvToDatabase(string csvPath, string connectionString)
    {
        // Step 1: Convert CSV to Excel for easier data manipulation
        string excelPath = Path.GetTempFileName() + ".xlsx";
        TextConverter.Process(csvPath, excelPath);
        
        // Step 2: Load Excel and process data
        Workbook workbook = new Workbook(excelPath);
        Worksheet sheet = workbook.Worksheets[0];
        
        // Step 3: Extract data and insert into database
        DataTable dataTable = sheet.Cells.ExportDataTable(0, 0, 
            sheet.Cells.MaxDataRow + 1, 
            sheet.Cells.MaxDataColumn + 1, 
            true);  // First row has headers
        
        // Step 4: Bulk insert into database
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
            {
                bulkCopy.DestinationTableName = "ImportedData";
                bulkCopy.WriteToServer(dataTable);
            }
        }
        
        // Clean up
        File.Delete(excelPath);
        
        Console.WriteLine($"✓ Imported {dataTable.Rows.Count} rows from {csvPath}");
    }
}

Web API Integration Example

Handle text file uploads and conversions in ASP.NET Core:

[HttpPost("convert-csv-to-excel")]
public IActionResult ConvertCsvToExcel(IFormFile file)
{
    try
    {
        // Save uploaded CSV
        string csvPath = Path.GetTempFileName();
        using (var stream = new FileStream(csvPath, FileMode.Create))
        {
            file.CopyTo(stream);
        }
        
        // Convert to Excel
        string excelPath = Path.ChangeExtension(csvPath, ".xlsx");
        TextConverter.Process(csvPath, excelPath);
        
        // Read result
        byte[] fileBytes = File.ReadAllBytes(excelPath);
        
        // Clean up
        File.Delete(csvPath);
        File.Delete(excelPath);
        
        return File(fileBytes, 
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Path.GetFileNameWithoutExtension(file.FileName) + ".xlsx");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Conversion error: {ex.Message}");
    }
}

SQL Script Generation

Convert Excel data to SQL INSERT statements:

using Aspose.Cells;

Workbook workbook = new Workbook("employees.xlsx");

SqlScriptSaveOptions sqlOptions = new SqlScriptSaveOptions();
sqlOptions.TableName = "Employees";
sqlOptions.OperatorType = SqlScriptOperatorType.Insert;
sqlOptions.Separator = ';';

workbook.Save("insert_employees.sql", sqlOptions);

Tips and Best Practices

Performance Optimization

  • Use LowCode API: Leverage TextConverter.Process() for optimized, single-line conversions.
  • Stream Processing: Use streams for large files to minimize memory usage.
  • Batch Operations: Process multiple files in parallel for high-throughput scenarios.
  • Resource Disposal: Dispose of workbook objects promptly when using traditional API.

Format Detection

  • File Extensions: Use standard extensions (.csv, .tsv, .xlsx) for automatic format detection.
  • Explicit Formats: Use traditional API with SaveFormat enum for non-standard extensions.
  • Validation: Verify input file format before conversion to avoid errors.

Data Quality

  • Encoding: Align encoding settings with target systems to avoid character corruption.
  • Delimiters: Choose appropriate delimiters based on data content (avoid characters present in data).
  • Headers: Ensure CSV/TSV files have consistent header rows for Excel conversion.
  • Empty Rows: Configure blank row handling to avoid unnecessary data gaps.

Production Deployment

  • Metered Licensing: Initialize licensing at application startup: new Metered().SetMeteredKey("PublicKey", "PrivateKey")
  • Error Handling: Wrap conversion calls in try-catch blocks with specific exception handling.
  • Thread Safety: The LowCode API is thread-safe; instantiate separate Workbook objects per thread for traditional API.
  • Logging: Implement logging for conversion metrics (file size, row count, duration).
  • Temporary Files: Clean up temporary files created during web application processing.

Integration Strategies

  • ETL Workflows: Use Text Converter as the first step in data pipelines.
  • API Endpoints: Return converted files directly from web APIs using streams.
  • Database Import: Convert CSV to Excel for data validation before database insertion.
  • Template Processing: Store XML/SQLSCRIPT templates externally for easy updates.

Common Issues and Resolutions

IssueResolution
File not foundEnsure the provided file path is correct and accessible
Unsupported file formatVerify the input format is supported; use standard file extensions
Incorrect format detectionUse traditional API with explicit SaveFormat for non-standard extensions
Character encoding issuesSet explicit encoding using TxtSaveOptions.Encoding with traditional API
Empty output fileCheck that input file contains data; verify worksheet is not empty
Delimiter not recognizedUse traditional API to set custom delimiter with TxtSaveOptions.Separator
Missing headers in CSVEnsure first row contains headers; use TxtLoadOptions.HasHeaderRow
Quote character issuesConfigure TxtSaveOptions.QuoteType for consistent quote handling
Large file performanceUse streaming mode or split file into smaller chunks

Frequently Asked Questions

What is Aspose.Cells Text Converter for .NET? A focused API for bidirectional conversion between Excel spreadsheets and text-based formats like CSV, TSV, XML, and SQLSCRIPT.

How does it differ from Aspose.Cells for .NET? Aspose.Cells is a multifunctional library. The Text Converter provides streamlined APIs specifically for text-focused conversion tasks.

Which formats are supported? XLS, XLSX, XLSM, CSV, TSV, XML, TXT, SQLSCRIPT, and more.

Can I convert CSV files to Excel? Yes! The Text Converter supports bidirectional conversion: Excel ↔ CSV, Excel ↔ TSV, Excel ↔ TXT, etc.

How does automatic format detection work? The LowCode API infers input and output formats from file extensions (.csv, .xlsx, etc.), eliminating the need to specify formats explicitly.

When should I use LowCode vs Traditional API? Use LowCode API (TextConverter.Process()) for simple, standard conversions. Use traditional API when you need custom delimiters, encoding, or format-specific options.

Can text generation settings be customized? Yes, using SaveOptions subclasses such as TxtSaveOptions, SqlScriptSaveOptions, etc. with the traditional Workbook API.

Do I need to specify the SaveFormat parameter? Not with the LowCode API—formats are automatically detected from file extensions. With traditional API, you can specify SaveFormat explicitly.

Can I convert multiple sheets to separate CSV files? Yes, iterate through worksheets and export each one individually, or use TxtSaveOptions.ExportAllSheets to control behavior.

Is metered licensing required? Metered licensing is optional but recommended for production to avoid evaluation limitations and track usage.


API Reference Summary

Key Classes

  • TextConverter: Static class providing simplified, format-detecting conversion methods
  • Workbook: Traditional API class for loading and manipulating Excel files
  • TxtSaveOptions: Configuration for CSV/TSV export with custom delimiters and encoding
  • TxtLoadOptions: Configuration for loading CSV/TSV files into Excel
  • SqlScriptSaveOptions: Configuration for SQL script generation
  • Metered: Class for configuring metered licensing

Essential Methods

  • TextConverter.Process(inputPath, outputPath): Single-line conversion with automatic format detection
  • Workbook.Save(path, SaveFormat): Save workbook in specified format
  • Workbook.Save(path, SaveOptions): Save workbook with custom options
  • Metered.SetMeteredKey(publicKey, privateKey): Initialize metered licensing

Key Properties (TxtSaveOptions)

  • Separator: Character used to separate values (default: comma for CSV, tab for TSV)
  • Encoding: Text encoding (UTF-8, UTF-16, etc.)
  • QuoteType: How to quote values (Always, AsNeeded, Never)
  • ExportAllSheets: Export all worksheets or only active sheet
  • KeepSeparatorsForBlankRow: Include separators for empty rows

Supported SaveFormat Values

  • SaveFormat.Csv: Comma-separated values
  • SaveFormat.Tsv: Tab-separated values
  • SaveFormat.Txt: Plain text
  • SaveFormat.Xml: XML data format
 English