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:
- 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.
- 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. - 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. - 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
EscapeCsvFieldmethod 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(','), ourParseCsvLinemethod 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.







![How to Convert XLSX to CSV Without Opening [5 Fast Ways]](https://blog.assetly.work/image/covers/_generic/04.webp)

