Saturday, May 23, 2026Today's Paper

Omni Apps

Convert Excel to CSV in C#: A High-Performance Guide
May 23, 2026 · 9 min read

Convert Excel to CSV in C#: A High-Performance Guide

Learn how to convert Excel to CSV in C# and CSV to Excel without Office Interop. Master fast, memory-efficient conversions using modern .NET libraries.

May 23, 2026 · 9 min read
C#.NETData EngineeringSoftware Architecture

Programmatic file conversion is a core requirement in enterprise software engineering. Across modern web apps, distributed data pipelines, and cloud services, developers frequently need to convert excel to csv c# or convert csv to excel c# to ensure seamless data interoperability.

Historically, many C# developers turned to Microsoft Office Interop for these tasks. However, relying on Interop in production is a dangerous architectural mistake. In this comprehensive guide, we will explore why you should completely abandon Interop, compare the best open-source alternatives in the modern .NET ecosystem, and provide production-ready C# implementations to handle file conversions rapidly, securely, and with minimal memory overhead.


Why You Must Avoid Microsoft Office Interop

When searching for an excel to csv converter c# solution, legacy tutorials often point toward Microsoft.Office.Interop.Excel. This library acts as a bridge to a locally installed copy of Microsoft Excel using COM (Component Object Model) marshaling.

While Interop might work on a developer's Windows workstation, it introduces critical flaws in production environments:

  1. Zero Cross-Platform Support: Interop requires Microsoft Office to be physically installed on the hosting server. This makes it impossible to run your application in Docker containers, on Linux servers, or in cloud environments like AWS Lambda, Google Cloud Run, or Azure App Services.
  2. Severe Performance Bottlenecks: Every time your code reads or writes a cell via Interop, it executes a cross-process COM call to a running instance of excel.exe. This is incredibly slow and CPU-heavy.
  3. Unmanaged Resource and Memory Leaks: Excel was not built to run headlessly as a server-side process. If your code encounters an unhandled exception before explicitly executing Marshal.ReleaseComObject, background Excel processes will hang indefinitely, eventually exhausting your server's RAM.
  4. Concurrency and Threading Issues: Excel is a single-threaded desktop application. Running concurrent conversion requests in an ASP.NET Core environment using Interop will trigger thread blocking, race conditions, and random process crashes.

To build robust, modern software, you must c# convert csv to excel without interop. By leveraging lightweight, fully managed .NET libraries, you can run conversions natively in memory across Windows, Linux, and macOS.


Top .NET Libraries for Excel and CSV Conversions

Before diving into the code, let's compare the most reliable, modern open-source libraries available on NuGet. Each has its strengths depending on whether you are reading or writing data.

Library Read Performance Write Performance Memory Usage License Best For
ExcelDataReader Extremely Fast N/A (Read-only) Exceptionally Low MIT Reading Excel and streaming to CSV
ClosedXML Moderate Fast Moderate MIT Writing formatted XLSX files from CSV
EPPlus Fast Fast Moderate PolyForm Non-Commercial / Commercial Feature-rich spreadsheet generation
MiniExcel Extremely Fast Extremely Fast Extremely Low Apache-2.0 Processing multi-gigabyte files

For this guide, we will use ExcelDataReader to convert Excel to CSV because it is unmatched in read speed and memory efficiency. For the reverse conversion (CSV to Excel), we will use ClosedXML due to its rich formatting capabilities and friendly, open-source API.


Step-by-Step: Convert Excel to CSV in C# (Without Interop)

Converting an Excel sheet to a CSV file requires reading spreadsheet rows and outputting them as a stream of comma-separated values. ExcelDataReader reads .xls and .xlsx files as a fast, forward-only stream, making it highly memory-efficient.

1. Install the NuGet Packages

Open your .NET terminal and install the required packages:

dotnet add package ExcelDataReader
dotnet add package System.Text.Encoding.CodePages

Note: Modern .NET Core/.NET 8 applications do not include all legacy character encodings by default. ExcelDataReader relies on System.Text.Encoding.CodePages to parse older .xls file encodings (such as codepage 1252).

2. Implementation Code

Here is a complete, production-ready class to convert excel file to csv c# while handling multi-character delimiters, multi-line cells, and comma-escaping constraints.

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

amespace ExcelToCsvDemo
{
    public static class ExcelToCsvConverter
    {
        public static void ConvertExcelToCsv(string excelFilePath, string csvOutputPath, char delimiter = ',')
        {
            // Step 1: Register the encoding provider to support legacy Excel codepages
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // Step 2: Open the Excel file as a read-only stream
            using var excelStream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var reader = ExcelReaderFactory.CreateReader(excelStream);
            using var csvWriter = new StreamWriter(csvOutputPath, false, Encoding.UTF8);

            // Step 3: Iterate through sheets, rows, and cells
            do
            {
                while (reader.Read())
                {
                    var columnCount = reader.FieldCount;
                    var rowValues = new string[columnCount];

                    for (int i = 0; i < columnCount; i++)
                    {
                        var cellValue = reader.GetValue(i)?.ToString() ?? string.Empty;
                        rowValues[i] = EscapeCsvField(cellValue, delimiter);
                    }

                    // Write the constructed row to the CSV
                    csvWriter.WriteLine(string.Join(delimiter.ToString(), rowValues));
                }
            } while (reader.NextResult()); // Moves to the next worksheet if present
        }

        private static string EscapeCsvField(string field, char delimiter)
        {
            // If the value contains delimiters, double quotes, or newlines, wrap it in double quotes
            if (field.Contains(delimiter) || field.Contains('\"') || field.Contains('\n') || field.Contains('\r'))
            {
                // Double quotes must be escaped by doubling them
                return $"\"{field.Replace("\"", "\"\"")}\"";
            }
            return field;
        }
    }
}

Why This Method Works Best:

  • Low Memory Overhead: Because ExcelReaderFactory.CreateReader() works as a forward-only reader, it does not load the entire workbook into RAM. You can easily process a 500MB Excel workbook with very little memory footprint.
  • Robust CSV Formatting: Our EscapeCsvField method ensures that cells containing literal commas, quotes, or carriage returns do not corrupt the structural format of the resulting CSV file.
  • Supports Multi-Sheet Files: The reader.NextResult() call ensures that every sheet in the workbook is processed and exported sequentially into the CSV output.

Step-by-Step: Convert CSV to Excel in C#

To convert csv to excel using c#, we need to read the raw, plain-text CSV file and build an organized open XML spreadsheet document. ClosedXML is an exceptional utility for this task, allowing us to generate beautiful .xlsx files without Office dependencies.

1. Install ClosedXML

Add ClosedXML to your project:

dotnet add package ClosedXML

2. Implementation Code

When implementing c# convert csv to excel, a common mistake is saving everything as plain text. This prevents Excel from running numeric formulas or formatting dates. Our code includes smart type parsing to convert strings into native double-precision floats, booleans, or dates where appropriate.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ClosedXML.Excel;

amespace ExcelToCsvDemo
{
    public static class CsvToExcelConverter
    {
        public static void ConvertCsvToExcel(string csvFilePath, string excelOutputPath, char delimiter = ',')
        {
            using var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add("Imported Data");

            int rowNumber = 1;
            using var reader = new StreamReader(csvFilePath, Encoding.UTF8);

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

                var columns = ParseCsvLine(line, delimiter);

                for (int colNumber = 0; colNumber < columns.Count; colNumber++)
                {
                    var rawValue = columns[colNumber];
                    var cell = worksheet.Cell(rowNumber, colNumber + 1);

                    // Infer and apply data types for a clean Excel sheet
                    if (double.TryParse(rawValue, out double numericValue))
                    {
                        cell.Value = numericValue;
                    }
                    else if (DateTime.TryParse(rawValue, out DateTime dateValue))
                    {
                        cell.Value = dateValue;
                    }
                    else if (bool.TryParse(rawValue, out bool boolValue))
                    {
                        cell.Value = boolValue;
                    }
                    else
                    {
                        cell.Value = rawValue;
                    }
                }
                rowNumber++;
            }

            // Format columns automatically for optimal visibility
            worksheet.Columns().AdjustToContents();
            workbook.SaveAs(excelOutputPath);
        }

        private static List<string> ParseCsvLine(string line, char delimiter)
        {
            var result = new List<string>();
            var currentToken = new StringBuilder();
            bool inQuotes = false;

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

                if (c == '\"')
                {
                    // Handle escaped quotes within quotes ("")
                    if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
                    {
                        currentToken.Append('\"');
                        i++; // Skip the second quote
                    }
                    else
                    {
                        inQuotes = !inQuotes; // Toggle quote state
                    }
                }
                else if (c == delimiter && !inQuotes)
                {
                    result.Add(currentToken.ToString());
                    currentToken.Clear();
                }
                else
                {
                    currentToken.Append(c);
                }
            }
            result.Add(currentToken.ToString());
            return result;
        }
    }
}

Key Architectural Features:

  • Custom CSV Parser: Unlike a naive string.Split(','), our ParseCsvLine method is a micro-state-machine that respects commas nested inside quotes. It handles fields like "Smith, John" without splitting them into separate columns.
  • Data Type Autofit: It intelligently translates strings like "1234.56" to actual numeric floats, allowing Excel users to apply formulas seamlessly after generation.
  • Excel Auto-Fit: Running worksheet.Columns().AdjustToContents() prevents the frustrating ### overflow truncation errors when users open the generated sheet.

Advanced Optimizations: Large Datasets & Regional Delimiters

When deploying file conversion engines to cloud microservices, high throughput and memory optimization become vital. Keep these production tips in mind:

1. Mitigating Out-of-Memory (OOM) Exceptions

Avoid loading entire workbooks into a DataSet in-memory representation. If you are handling sheets with over 100,000 rows, use streaming pipelines. Avoid assigning cell objects inside massive loops; write directly to stream formats whenever possible.

2. Culture-Specific CSV Delimiters

Not all CSVs use commas. In many European regions, the standard list separator is a semicolon (;) because commas are reserved for decimal separators. Design your methods with customizable delimiter characters so they adapt to global localization parameters.

3. Asynchronous File Stream Processing

In high-concurrency web applications, leverage non-blocking IO. Instead of executing blocking operations like File.Open(), wrap file handling inside standard asynchronous tasks or utilize modern pipeline tools such as System.IO.Pipelines to streamline memory allocation.


Frequently Asked Questions

Can I run this conversion code in a Docker container on Linux?

Yes! Both ExcelDataReader and ClosedXML are written in 100% managed C# and do not depend on native Windows APIs or GDI+ libraries. This makes them perfectly suited to run on Linux containers, cloud hosting platforms, or macOS.

Why does ExcelDataReader fail with a 'No encoding found' error?

If you see System.NotSupportedException: No encoding found for codepage 1252, it is because modern .NET runtimes omit extended character sets by default. To resolve this, call Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); at your application's startup before processing any files.

How can I convert multiple Excel sheets to separate CSV files?

Since CSV files structurally support only a single sheet, you must write a loop that saves each spreadsheet as an independent document. In our C# code, change the do...while (reader.NextResult()) block to write to distinct files (e.g., sheet1.csv, sheet2.csv) based on reader.Name.

What is the fastest library for handling multi-gigabyte files?

If you are dealing with files containing millions of records, use MiniExcel. It is specifically optimized to perform streaming operations on massive files with negligible memory use, bypassing the rich styling abstractions of ClosedXML.


Conclusion

Programmatically converting spreadsheets doesn't require bulky, legacy software components like Office Interop. By using ExcelDataReader to convert excel to csv c# and ClosedXML to convert csv to excel c#, you gain total execution speed, platform independence, and architectural stability.

When writing file conversion logic for your application, always remember to respect data types, escape delimiters correctly, and stream processing actions to protect your CPU and RAM. Implement these modern, non-Interop solutions today to future-proof your .NET enterprise software stack.

Related articles
XLS to CSV Command Line: The Ultimate Automation Guide
XLS to CSV Command Line: The Ultimate Automation Guide
Learn how to convert XLS to CSV via command line on Windows, Linux, and macOS. Discover the best tools for xls to csv command line conversion without Excel.
May 23, 2026 · 10 min read
Read →
XLS to CSV in C#: Complete Conversion Guide (and CSV to XLS)
XLS to CSV in C#: Complete Conversion Guide (and CSV to XLS)
Learn how to convert XLS to CSV and CSV to XLS in C# using high-performance, open-source libraries. Avoid COM Interop with these cross-platform solutions.
May 23, 2026 · 14 min read
Read →
How to Run an XLS to CSV Batch Conversion: 4 Fast Methods
How to Run an XLS to CSV Batch Conversion: 4 Fast Methods
Need to run an XLS to CSV batch conversion? Discover the fastest, free ways to batch convert Excel files to CSV using Python, VBA, PowerShell, and more.
May 23, 2026 · 13 min read
Read →
Mastering C# CSV and Excel: Read, Convert, and Export Data
Mastering C# CSV and Excel: Read, Convert, and Export Data
Learn how to handle C# CSV and Excel integrations without Office Interop. Discover performant ways to convert, import, and read files into DataTables.
May 22, 2026 · 10 min read
Read →
Mastering Markdown in Databricks: The Ultimate Notebook Guide
Mastering Markdown in Databricks: The Ultimate Notebook Guide
Learn how to use markdown in Databricks to format text, build beautiful tables, render LaTeX math, and display dynamic HTML. Perfect your notebook documentation.
May 22, 2026 · 12 min read
Read →
Postgres CSV to Table: A Complete Guide to Import & Export
Postgres CSV to Table: A Complete Guide to Import & Export
Learn how to import a Postgres CSV to table using COPY, \copy, pgAdmin, and Python. Master bulk loading, fix errors, and export data back to CSV.
May 22, 2026 · 14 min read
Read →
How to Convert XLSX to CSV Without Opening [5 Fast Ways]
How to Convert XLSX to CSV Without Opening [5 Fast Ways]
Discover 5 powerful ways to convert XLSX to CSV without opening Microsoft Excel. Master Python, PowerShell, CLI tools, and Excel context workarounds.
May 22, 2026 · 12 min read
Read →
How to Convert Excel to CSV via Command Line: 5 Fast Ways
How to Convert Excel to CSV via Command Line: 5 Fast Ways
Learn how to convert Excel to CSV via command line and vice versa. Step-by-step tutorial using csvkit, LibreOffice, PowerShell, Python, and ssconvert.
May 22, 2026 · 13 min read
Read →
Mastering Base64 Kotlin: Native, JVM, and Android Implementation Guide
Mastering Base64 Kotlin: Native, JVM, and Android Implementation Guide
Learn how to easily implement base64 kotlin encoding and decoding. Master the modern Kotlin standard library, legacy JVM APIs, Android utilities, and multiplatform.
May 21, 2026 · 14 min read
Read →
How to Create and Export a CSV Pivot Table: The Ultimate Guide
How to Create and Export a CSV Pivot Table: The Ultimate Guide
Learn how to create a pivot table from a CSV file in Excel, Google Sheets, or Python, and how to successfully export a pivot table back to a flat CSV.
May 21, 2026 · 18 min read
Read →
Related articles
Related articles