Saturday, May 23, 2026Today's Paper

Omni Apps

Convert XLSX to CSV in C#: Complete Guide (Without Excel)
May 23, 2026 · 14 min read

Convert XLSX to CSV in C#: Complete Guide (Without Excel)

Learn how to convert XLSX to CSV in C# and CSV to XLSX using fast, modern .NET libraries—completely cross-platform and without Microsoft Excel installed.

May 23, 2026 · 14 min read
dotnetC# ProgrammingData Integration

When building enterprise web applications, cloud microservices, or automated ETL data pipelines, spreadsheet format conversion is a ubiquitous requirement. Developers frequently need to translate raw, structured spreadsheets from a rich workbook format into an easily digestible plain-text representation—and vice versa. Achieving a fast, reliable, and scalable conversion between xlsx to csv c# and csv to xlsx c# is essential for high-performance applications.

Historically, developers relied on Microsoft Office COM Interop assemblies to handle these spreadsheets. However, running Microsoft Excel on a server is notoriously slow, fragile, and outright warned against by Microsoft. Fortunately, modern .NET ecosystems allow you to convert xlsx to csv c# and perform the inverse convert csv to xlsx c# operations cleanly, without installing Office or Excel on your machine.

In this comprehensive developer's guide, we will walk through the absolute best practices, architectural choices, and complete, production-ready code samples to convert spreadsheet formats efficiently. We will focus entirely on c# convert xlsx to csv without excel utilizing high-performance, open-source libraries that are fully cross-platform and optimized for .NET Core, .NET 5, .NET 6, .NET 7, and .NET 8+.

The Fatal Flaws of Office Interop: Why You Must Avoid It

For years, the default answer to Excel manipulation in .NET was Microsoft.Office.Interop.Excel. This library works by spinning up a hidden instance of the Excel desktop application (excel.exe) in the background and controlling it via Component Object Model (COM) calls. While this approach perfectly mimics user interactions, it introduces critical problems when deployed in professional server environments:

  • No Non-Windows Support: Office Interop is tightly bound to the Windows operating system and registry. It is completely incompatible with Linux-based Docker containers, AWS ECS/Fargate, Azure App Services running on Linux, or macOS development environments.
  • Severe Performance Bottlenecks: Spawning a GUI application like Excel just to parse or write files consumes massive CPU and RAM. Interop calls pass data across processes (marshalling), which is incredibly slow.
  • Memory Leaks & Zombie Processes: If your C# application crashes or fails to call Marshal.ReleaseComObject() and GC.Collect() in a very precise order, background excel.exe processes will leak. Over time, these zombie processes will saturate your server's memory, eventually crashing the entire machine.
  • Thread Safety Issues: Microsoft Excel was designed as a single-user desktop application. Running it concurrently in a multi-threaded web API or background worker will trigger race conditions, random deadlocks, and silent data corruption.
  • Licensing Violations: Microsoft's licensing agreements strictly prohibit running Office applications in unattended, multi-user web/server environments.

Because of these limitations, enterprise-grade architectures require that you convert xlsx to csv c# and convert csv to xlsx c# without any dependency on the desktop Excel application. By decoupling your .NET code from Excel, you achieve microsecond-level processing speeds, near-zero RAM usage, and 100% cloud-native cross-platform compatibility.

The Top .NET Libraries for Spreadsheet Conversions

To perform spreadsheet conversions without Office, the .NET ecosystem offers several high-quality, open-source libraries. Each has distinct architectural designs, strengths, and licensing structures:

  1. ExcelDataReader: A lightweight, highly performant, streaming, forward-only reader written in pure C#. It is specifically optimized to read Excel files fast with a microscopic memory footprint. Because it reads files as a forward stream, it doesn't load the entire workbook into memory at once, making it the perfect choice to convert xlsx to csv c# for multi-gigabyte files.
  2. ClosedXML: A developer-friendly wrapper around Microsoft's official DocumentFormat.OpenXml SDK. It exposes a clean object model representing workbooks, worksheets, cells, and ranges. ClosedXML is ideal for writing spreadsheets, formatting cells, and handling c# csv to xlsx transitions since it supports both reading and generating standard OpenXML (.xlsx) files under a permissive MIT license.
  3. EPPlus: A widely popular library for both reading and writing XLSX files. It boasts exceptional formatting and charting capabilities. Note: Since version 5, EPPlus transitioned to a commercial PolyForm Noncommercial license. If you require a fully open-source, commercially free tool, ClosedXML or ExcelDataReader are preferred.
  4. Sylvan.Data.Excel & Sylvan.Data.Csv: A modern, incredibly fast library designed by Ben Watson. It is often benchmarked as the fastest Excel-to-CSV converter in the .NET world, specifically optimized to stream data directly into database-friendly formats.

By combining these libraries, we can build efficient pipelines that handle bidirectional spreadsheet conversions flawlessly. Let's dive into the implementation.

High-Performance XLSX to CSV in C# (Without Excel)

When writing a c# xlsx to csv converter, memory footprint is your chief concern. If you load a massive spreadsheet into a heavy Document Object Model (DOM) structure, your server's garbage collector (GC) will struggle, causing severe performance degradation.

Below, we demonstrate the optimal way to write a c# convert xlsx to csv workflow using ExcelDataReader. This solution reads rows in a streaming fashion, escapes characters properly, handles commas and quotes according to RFC 4180 rules, and uses modern C# syntax.

First, install the library via the NuGet Package Manager:

dotnet add package ExcelDataReader

(Note: If you are running on .NET Core or modern .NET, you must register the encoding provider to support legacy Excel text encoding pages.)

Here is the complete, production-grade C# code:

using System;
using System.IO;
using System.Text;
using ExcelDataReader;

public static class XlsxToCsvConverter
{
    /// <summary>
    /// Converts a local XLSX spreadsheet to a RFC 4180-compliant CSV file.
    /// </summary>
    /// <param name="xlsxPath">The path to the input XLSX file.</param>
    /// <param name="csvPath">The path where the output CSV will be saved.</param>
    /// <param name="delimiter">The delimiter character to use (default is comma).</param>
    public static void Convert(string xlsxPath, string csvPath, string delimiter = ",")
    {
        if (string.IsNullOrWhiteSpace(xlsxPath) || !File.Exists(xlsxPath))
            throw new FileNotFoundException($"Source XLSX file not found: {xlsxPath}");

        // Step 1: Register the encoding provider. Required for .NET Core / .NET 5+ 
        // to handle older spreadsheet text encodings correctly.
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        // Step 2: Open file streams with optimized sharing options
        using var sourceStream = new FileStream(xlsxPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        using var reader = ExcelReaderFactory.CreateReader(sourceStream);
        using var destinationWriter = new StreamWriter(csvPath, false, Encoding.UTF8);

        // Step 3: Loop through all worksheets inside the workbook
        do
        {
            // Read row-by-row to maintain an ultra-low memory profile
            while (reader.Read())
            {
                int fieldCount = reader.FieldCount;
                var rowFields = new string[fieldCount];

                for (int i = 0; i < fieldCount; i++)
                { 
                    object rawValue = reader.GetValue(i);
                    string rawString = rawValue?.ToString() ?? string.Empty;

                    // Step 4: Properly escape CSV values to prevent corrupt formatting
                    rowFields[i] = EscapeCsvField(rawString, delimiter);
                }

                // Step 5: Join fields with the delimiter and write the line
                destinationWriter.WriteLine(string.Join(delimiter, rowFields));
            }
        } while (reader.NextResult()); // Moves to the next worksheet if present
    }

    /// <summary>
    /// Escapes field values containing delimiters, quotes, or newlines in compliance with RFC 4180.
    /// </summary>
    private static string EscapeCsvField(string field, string delimiter)
    {
        if (string.IsNullOrEmpty(field))
            return string.Empty;

        // If the value contains quotes, newlines, or the delimiter, it must be enclosed in quotes.
        bool requiresQuotes = field.Contains(delimiter) || 
                              field.Contains("\"") || 
                              field.Contains("\r") || 
                              field.Contains("\n");

        if (requiresQuotes)
        { 
            // Escape existing double-quotes by doubling them (e.g., " became "")
            string escapedValue = field.Replace("\"", "\"\"");
            return $"\"{escapedValue}\"";
        }

        return field;
    }
}

How This Code Works Under the Hood

  • Streaming Architecture: Instead of building a heavy memory tree of the Excel workbook, ExcelReaderFactory.CreateReader() sets up a streaming, forward-only connection. This is identical to how an IDataReader streams database records, ensuring memory remains constant whether processing 10 rows or 10,000,000 rows.
  • Encoding Provider Registration: Excel files store data using various ANSI code pages. Modern .NET runtimes only bundle basic UTF-8 and Unicode encodings out of the box to keep the runtime lightweight. Registering CodePagesEncodingProvider.Instance allows ExcelDataReader to successfully read strings from workbooks saved with regional or older encodings.
  • RFC 4180 Escaping Logic: Many naive converters simply concatenate values with a comma. However, if a cell contains an actual comma (e.g., "Chicago, IL") or a newline, the resulting CSV structure will be broken. Our helper function EscapeCsvField dynamically doubles existing quotes and wraps the field in double quotes to preserve data integrity.

Converting CSV to XLSX in C# (Without Excel)

Generating spreadsheets from raw text data is a highly sought-after capability. When converting a CSV back to an Excel spreadsheet (c# csv to xlsx), you want a library that reads the text fields, dynamically infers correct data types, inserts them into standard XLSX grids, and auto-sizes column widths for maximum readability.

To achieve this, we will use ClosedXML, an elegant, feature-rich library that operates directly on OpenXML markup.

Install ClosedXML via NuGet:

dotnet add package ClosedXML

Here is a robust, clean implementation of a c# convert csv to xlsx utility class:

using System;
using System.IO;
using ClosedXML.Excel;

public static class CsvToXlsxConverter
{
    /// <summary>
    /// Parses a CSV file and writes it into a fully styled XLSX spreadsheet.
    /// </summary>
    /// <param name="csvPath">The input CSV file path.</param>
    /// <param name="xlsxPath">The output XLSX file path.</param>
    /// <param name="delimiter">The delimiter character parsing the CSV.</param>
    public static void Convert(string csvPath, string xlsxPath, char delimiter = ',')
    {
        if (string.IsNullOrWhiteSpace(csvPath) || !File.Exists(csvPath))
            throw new FileNotFoundException($"Source CSV file not found: {csvPath}");

        // Step 1: Create a brand new OpenXML workbook
        using var workbook = new XLWorkbook();
        var worksheet = workbook.Worksheets.Add("Imported Data");

        // Step 2: Stream-read the CSV file to preserve memory
        using var reader = new StreamReader(csvPath, System.Text.Encoding.UTF8);
        int currentRowIndex = 1;

        while (!reader.EndOfStream)
        { 
            string line = reader.ReadLine();
            if (line == null) continue;

            // Step 3: Extract structured CSV tokens honoring quoted values
            string[] tokens = ParseCsvLine(line, delimiter);

            for (int colIndex = 0; colIndex < tokens.Length; colIndex++)
            { 
                string rawValue = tokens[colIndex];
                var cell = worksheet.Cell(currentRowIndex, colIndex + 1);

                // Step 4: Map values to strong types to ensure Excel can apply formatting
                if (double.TryParse(rawValue, out double numericValue))
                { 
                    cell.Value = numericValue;
                }
                else if (bool.TryParse(rawValue, out bool booleanValue))
                { 
                    cell.Value = booleanValue;
                }
                else if (DateTime.TryParse(rawValue, out DateTime dateValue))
                { 
                    cell.Value = dateValue;
                    cell.Style.DateFormat.Format = "yyyy-mm-dd";
                }
                else
                { 
                    cell.Value = rawValue;
                }
            }
            currentRowIndex++;
        }

        // Step 5: Autofit columns to prevent layout truncating (e.g. ### errors)
        worksheet.Columns().AdjustToContents();

        // Step 6: Write to disk
        workbook.SaveAs(xlsxPath);
    }

    /// <summary>
    /// Robust state machine CSV parser that handles quoted delimiters and double quotes.
    /// </summary>
    private static string[] ParseCsvLine(string line, char delimiter)
    { 
        var fields = new System.Collections.Generic.List<string>();
        var currentField = new System.Text.StringBuilder();
        bool inQuotes = false;

        for (int i = 0; i < line.Length; i++)
        { 
            char character = line[i];

            if (character == '"')
            { 
                // Handle escaped double quotes (RFC 4180)
                if (inQuotes && i + 1 < line.Length && line[i + 1] == '"')
                { 
                    currentField.Append('"');
                    i++; // Skip next quote
                }
                else
                { 
                    inQuotes = !inQuotes; // Toggle quote state
                }
            }
            else if (character == delimiter && !inQuotes)
            { 
                // Delimiter reached outside of a quoted block; close field
                fields.Add(currentField.ToString());
                currentField.Clear();
            }
            else
            { 
                currentField.Append(character);
            }
        }
        
        fields.Add(currentField.ToString());
        return fields.ToArray();
    }
}

Key Highlights of the CSV to XLSX Logic

  1. Strong Type Detection: A massive flaw in basic CSV-to-Excel scripts is writing everything as a text string. This results in green "Numbers stored as text" warnings inside Excel and prevents users from running simple mathematical formulas like =SUM(). By utilizing TryParse blocks, we map numerical, boolean, and date formats to actual typed values, enabling immediate, native Excel data manipulation.
  2. Robust RFC 4180 Parsing: Relying on string.Split(',') is a dangerous anti-pattern. If a column contains string values like "Johnson, Robert", Split will slice that single name into separate cells, throwing off your column structure. Our state-machine parser handles nested quotes, escaped double quotes, and internal separators cleanly.
  3. Column Width Optimization: ClosedXML allows you to call worksheet.Columns().AdjustToContents(). This automatically evaluates text widths and expands column sizes, avoiding the common and frustrating ### display errors when users open their generated files.

Advanced Challenges & Performance Optimizations

When converting thousands of files inside a business environment, simple code loops can fall short. Here are critical engineering concerns and solutions to help make your conversion routines production-grade:

1. Handling Giant Datasets and Garbage Collection

If your server converts a 100MB XLSX file, loading it into an in-memory workbook like EPPlus or ClosedXML will expand the file's payload by 5x to 10x inside memory. This triggers heavy gen-2 Garbage Collection sweeps, severely stalling API response rates.

  • Solution: Always prefer streaming solutions (like ExcelDataReader) when translating XLSX down to CSV. If you must write massive CSVs to XLSX, consider using memory-optimized libraries like Sylvan or MiniExcel. These libraries write XML nodes directly to streams without constructing cell object graphs.

2. Cross-Platform Culture and Globalization Issues

Parsing numbers and dates is highly dependent on system culture settings. For instance, in European countries like Germany, commas are used as decimals (1.234,56), and semicolons (DefaultSeparator = ";") act as CSV separators.

  • Solution: Always pass a unified culture context when parsing data programmatically. For robust conversions, parsing utilizing CultureInfo.InvariantCulture ensures your code performs uniformly whether hosted on a US-based Azure server or a locally hosted European workstation.

3. Processing Multi-Sheet Workbooks

Unlike CSV files (which only hold a single flat grid of rows), XLSX workbooks can contain multiple worksheets.

  • Solution: When running xlsx to csv c# conversions on files with multiple sheets, you must decide how to output them. You can either append a sheet identifier index to the CSV name (e.g., report_Sheet1.csv, report_Sheet2.csv) or dynamically write them to separate directories. The code example using reader.NextResult() in Section 3 naturally traverses through sheets so you can write a loop to generate distinct files per worksheet automatically.

4. Deploying to Linux Containers (Docker)

When running .NET applications in Linux containers (especially minimal images like Alpine), you might encounter issues with font availability and globalization context.

  • Solution: Ensure your Dockerfile includes native culture assets. For Alpine-based containers, install the icu-libs package and set the environment variable DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false to allow proper Unicode formatting and numeric culture parsing inside the libraries.

FAQ: XLSX and CSV Conversion in .NET

Can I convert XLSX to CSV on Linux or macOS?

Absolutely! Since we do not rely on COM Interop or Windows-only registries, libraries like ExcelDataReader, ClosedXML, and Sylvan are completely cross-platform. They run perfectly inside Docker containers built on Debian or Alpine Linux, Azure App Services on Linux, and macOS local development setups.

What is the fastest library to convert Excel to CSV in C#?

In multiple standard industry benchmarks, Sylvan.Data.Excel coupled with Sylvan.Data.Csv consistently achieves the fastest read/write times. It uses highly optimized, low-allocation algorithms and spans almost zero heap allocations. If raw speed is your bottleneck, Sylvan is highly recommended. ExcelDataReader is a very close second, offering extremely stable, long-term community support.

How do I handle CSV files that use semicolons instead of commas?

You can easily pass a semicolon string ";" or character ';' into our custom Convert methods from our examples. The parsing state machines and writing helpers are completely parameterized to support custom delimiters (like tabs, semicolons, or pipes) dynamically.

How do I format dates properly during CSV-to-Excel conversion?

When parsing CSV rows into ClosedXML cells, check if the string parses cleanly as a DateTime. If it does, assign the parsed DateTime directly to the cell's value, and assign a standardized formatting mask, such as cell.Style.DateFormat.Format = "yyyy-mm-dd". This formats the display in Excel without altering the underlying raw data.

Is EPPlus completely free to use?

No. While EPPlus versions up to 4.x remain under the highly permissive LGPL license, version 5 and higher are distributed under the PolyForm Noncommercial license. If you are developing a closed-source commercial product or building software inside a business organization, you must purchase a license for modern EPPlus. For free, production-ready alternatives, ClosedXML (MIT) and ExcelDataReader (MIT) are excellent options.

Conclusion

Building file translation workflows doesn't require bulky software packages or outdated COM Interop architectures. Programmatically converting xlsx to csv c# and csv to xlsx c# is straightforward, reliable, and exceptionally fast when using robust, lightweight open-source .NET libraries.

By leveraging ExcelDataReader for stream-reading worksheets, and ClosedXML for dynamically writing and formatting target sheets, developers can construct fast, secure pipelines. These solutions run smoothly in Linux Docker containers, cloud serverless routines, or localized automation workers. Integrating correct RFC 4180 escaping and typing rules guarantees your data remains perfectly consistent, clean, and professional.

Choose the library setup that matches your licensing and performance goals, drop in the corresponding class files, and scale your data pipelines without Excel.

Related articles
Excel Convert CSV to XML: The Ultimate Step-by-Step Guide
Excel Convert CSV to XML: The Ultimate Step-by-Step Guide
Learn the exact steps to excel convert csv to xml. This comprehensive guide covers XML schema mapping, Power Query, and programmatic C# OpenXML options.
May 22, 2026 · 12 min read
Read →
Excel VBA CSV Export: The Ultimate Automated Guide
Excel VBA CSV Export: The Ultimate Automated Guide
Master Excel VBA CSV export procedures. Learn to convert Excel to CSV, import files with leading zeros, handle special characters, and write VB.NET solutions.
May 22, 2026 · 12 min read
Read →
How to Use a Passüord Generator for Bulletproof Security
How to Use a Passüord Generator for Bulletproof Security
Looking for a reliable passüord generator? Learn how to secure your accounts with random passwords, passkeys, and top-tier password generator tools.
May 23, 2026 · 13 min read
Read →
Laravel Export CSV: The Ultimate Guide to Fast, Memory-Safe Exports
Laravel Export CSV: The Ultimate Guide to Fast, Memory-Safe Exports
Master Laravel export CSV techniques. Learn to build blazing-fast, memory-safe CSV exports using Maatwebsite Laravel Excel and native PHP database streams.
May 23, 2026 · 12 min read
Read →
How to Change to SVG File: The Ultimate Vectorization Guide
How to Change to SVG File: The Ultimate Vectorization Guide
Want to change to svg file format without losing quality? Learn how to turn any PNG or JPG into a scalable, crisp vector for web design or Cricut crafting.
May 23, 2026 · 12 min read
Read →
How to Count Macros Free: The Ultimate Step-by-Step Guide & Quiz
How to Count Macros Free: The Ultimate Step-by-Step Guide & Quiz
Ready to hit your fitness goals without paying for premium apps? Learn how to count macros free using our step-by-step math formulas, quizzes, and tracking tools.
May 23, 2026 · 14 min read
Read →
Whois auDA Lookup: How to Check .AU Domain Ownership
Whois auDA Lookup: How to Check .AU Domain Ownership
Looking to verify a .au domain registration? Read our ultimate guide to the whois auda lookup tool to trace ownership, check registrar info, and verify ABNs.
May 23, 2026 · 14 min read
Read →
Mastering Base64 Delphi: How to Encode and Decode Strings, Files, and Streams
Mastering Base64 Delphi: How to Encode and Decode Strings, Files, and Streams
Discover the ultimate guide to Base64 Delphi encoding. Master modern TBase64Encoding, avoid Unicode bugs, handle large files via streams, and support legacy IDEs.
May 23, 2026 · 12 min read
Read →
Investopedia Compound Interest Calculator: Ultimate Growth Guide
Investopedia Compound Interest Calculator: Ultimate Growth Guide
Discover how to maximize your savings with the Investopedia compound interest calculator. Learn formulas, Excel tricks, and how compounding builds wealth.
May 23, 2026 · 18 min read
Read →
Gross Profit Margin vs Net Profit Margin: The Ultimate Guide
Gross Profit Margin vs Net Profit Margin: The Ultimate Guide
Understand the differences between gross profit margin net profit margin, how to calculate both with formulas, and what they reveal about your business.
May 23, 2026 · 16 min read
Read →
Related articles
Related articles