Saltar al pie de página
USANDO IRONXL

Cómo usar una biblioteca CSV en C# para leer y escribir archivos

Working with CSV files in C# often goes beyond simple reading and writing. Developers need reliable CSV file handling, smooth data import/export, and easy integration with spreadsheet workflows. While free libraries like CsvHelper cover basic CSV operations, they sometimes fall short when you need Excel workbook support, high performance, or consistent handling of rows, columns, and data types.

IronXL solves these challenges by providing a single .NET library that's capable of handling CSV and Excel formats seamlessly, without requiring Microsoft Office. It offers robust functionality for reading and writing CSV, mapping custom class objects, and converting between comma separated values and Excel. All in a high-performance, low-memory workflow suitable for both desktop and web applications.

How to Get Started with IronXL?

Installing IronXL takes just seconds through NuGet Package Manager. Open your Package Manager Console in Visual Studio and run:

Install-Package IronXL.Excel

After installation, add the IronXL namespace to your C# file:

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

IronXL works across Windows, Linux, and macOS environments, supporting .NET Framework 4.6.2+ and .NET Core/5/6/7/8+. The library operates independently without Microsoft Office dependencies, making it ideal for server deployments and cloud applications. For detailed setup instructions, visit the IronXL installation guide.

How to Read CSV Files with IronXL?

IronXL supports reading CSV files with ease, with the entire process following an intuitive pattern. The library automatically handles common challenges like encoding detection and delimiter identification, issues that developers frequently encounter when parsing CSV data:

// Load a CSV file into a WorkBook
WorkBook workBook = WorkBook.Load("sales_data.csv");
// Access the imported worksheet
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Read specific cell values
string customerName = workSheet["A2"].StringValue;
decimal orderAmount = workSheet["B2"].DecimalValue;
// iterating from row 1 to skip the header row
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    Console.WriteLine($"Customer: {row.Columns[0].Value}, Amount: {row.Columns[1].Value}");
}
// Load a CSV file into a WorkBook
WorkBook workBook = WorkBook.Load("sales_data.csv");
// Access the imported worksheet
WorkSheet workSheet = workBook.DefaultWorkSheet;
// Read specific cell values
string customerName = workSheet["A2"].StringValue;
decimal orderAmount = workSheet["B2"].DecimalValue;
// iterating from row 1 to skip the header row
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    Console.WriteLine($"Customer: {row.Columns[0].Value}, Amount: {row.Columns[1].Value}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code loads a CSV file into a WorkBook object, which provides full spreadsheet functionality. The DefaultWorkSheet property gives immediate access to the CSV data. Individual cells can be accessed using familiar Excel notation like "A2", with built-in type conversion methods (StringValue, DecimalValue, IntValue) ensuring proper data handling. The for loop demonstrates row iteration, treating each row as a collection of cells. We've used a loop that will automatically skip the first row as it's a header row; however, if you wanted to keep your header as part of the output, just use:

foreach (var row in workSheet.Rows)
{
    Console.WriteLine($"{row.Columns[0].Value}, {row.Columns[1].Value}");
}
foreach (var row in workSheet.Rows)
{
    Console.WriteLine($"{row.Columns[0].Value}, {row.Columns[1].Value}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For more complex scenarios, explore the complete reading tutorial.

Output

How to Use a C# CSV Library for Reading and Writing Files: Figure 1 - Read CSV file output

For advanced scenarios, developers can map CSV rows into custom class objects by iterating through each row and assigning cell values to object properties. This approach provides a clean way to work with structured data in C#.

How to Write CSV Files in C#?

Creating CSV files with IronXL supports multiple approaches, from building new spreadsheets to converting existing data structures. This flexibility makes it ideal for data export scenarios:

// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("inventory");
// Add header row
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";
// Add data rows
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 100;
workSheet["C2"].Value = 19.99;
// Save as CSV
workBook.SaveAsCsv("inventory.csv");
// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("inventory");
// Add header row
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";
// Add data rows
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 100;
workSheet["C2"].Value = 19.99;
// Save as CSV
workBook.SaveAsCsv("inventory.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This example creates a new workbook from scratch and populates it with data. The SaveAsCsv() method exports the worksheet to CSV format, automatically handling proper formatting and delimiters. IronXL preserves data types during export, ensuring numbers remain numeric rather than converting everything to strings. The SaveAsCsv method supports custom delimiters when needed.

Output

How to Use a C# CSV Library for Reading and Writing Files: Figure 2 - Newly created CSV file using IronXL

For existing data, IronXL can convert DataTables directly:

DataTable dataTable = GetDataFromDatabase();
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("export");
workSheet.InsertDataTable(dataTable, "A1");
workBook.SaveAsCsv("export.csv");
DataTable dataTable = GetDataFromDatabase();
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("export");
workSheet.InsertDataTable(dataTable, "A1");
workBook.SaveAsCsv("export.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Can IronXL Convert Between CSV and Excel Formats?

IronXL's standout feature is seamless conversion between CSV and Excel formats. This capability eliminates the need for separate libraries when working with different file types, a common requirement discussed by developers:

// Convert CSV to Excel
WorkBook csvWorkBook = WorkBook.Load("data.csv");
csvWorkBook.SaveAs("data.xlsx");
// Convert Excel to CSV
WorkBook xlsxWorkBook = WorkBook.Load("report.xlsx");
xlsxWorkBook.SaveAsCsv("report.csv");
// Convert CSV to Excel
WorkBook csvWorkBook = WorkBook.Load("data.csv");
csvWorkBook.SaveAs("data.xlsx");
// Convert Excel to CSV
WorkBook xlsxWorkBook = WorkBook.Load("report.xlsx");
xlsxWorkBook.SaveAsCsv("report.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These conversions preserve data integrity, including numeric types, dates, and formulas where applicable. When converting multi-sheet Excel files to CSV, IronXL creates separate CSV files for each worksheet:

WorkBook multiSheetWorkBook = WorkBook.Load("multi_sheet.xlsx");
multiSheetWorkBook.SaveAsCsv("output.csv");
// Creates: output.Sheet1.csv, output.Sheet2.csv, etc.
WorkBook multiSheetWorkBook = WorkBook.Load("multi_sheet.xlsx");
multiSheetWorkBook.SaveAsCsv("output.csv");
// Creates: output.Sheet1.csv, output.Sheet2.csv, etc.
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The conversion process handles complex Excel features gracefully. Formulas are evaluated to their values, formatting is preserved where possible, and data validation rules are maintained in the Excel format. Learn more about Excel to CSV conversion in the documentation.

How to Use a C# CSV Library for Reading and Writing Files: Figure 3 - Multi-paged Excel file saved as separate CSV files

And to see how one of these CSV files holds up against the original .xlsx file, let's take a look at the output.Customers file opened in notepad vs. the Customers sheet as viewed in Excel:

How to Use a C# CSV Library for Reading and Writing Files: Figure 4 - Original Excel format file vs. the converted CSV file

Empiece con IronXL ahora.
green arrow pointer

Why Choose IronXL for CSV File Handling?

When evaluating C# CSV libraries, developers consider factors like ease of use, feature completeness, and long-term support. IronXL addresses these needs comprehensively:

How to Use a C# CSV Library for Reading and Writing Files: Figure 5 - IronXL vs. csv-only libraries comparison table

Beyond basic CSV operations, IronXL provides enterprise features like password-protected file handling, cell styling preservation, and formula calculation. The unified API means developers learn one library for all spreadsheet needs, reducing complexity in projects that handle multiple file formats.

Cross-platform compatibility ensures consistent behavior across development and production environments. The library's managed code approach eliminates platform-specific dependencies, simplifying deployment and maintenance. For detailed feature comparisons, see the IronXL features page.

Conclusion

IronXL streamlines the entire workflow of reading and writing CSV files, converting between Excel and CSV, and handling advanced spreadsheet features. It’s more than just another CSV library, it’s a complete spreadsheet toolset for .NET developers.

By combining a clean API, comprehensive support, and enterprise-grade testing, IronXL helps developers avoid wasted time chasing bugs, patching with ad-hoc pull requests, or relying on fragmented open-source packages.

If your project requires reliable, high-performance spreadsheet functionality, IronXL is the right choice. It empowers you to manage files, process data, and build scalable solutions, all with professional stability and ease of use.

Ready to simplify your CSV and Excel handling? Start with a free trial starting at $liteLicense, which include professional support and ongoing updates.

Preguntas Frecuentes

¿Qué es IronXL y cómo ayuda con archivos CSV en C#?

IronXL es una poderosa biblioteca de C# que permite a los desarrolladores leer, escribir y convertir archivos CSV sin problemas. Ofrece soporte extendido para libros de trabajo de Excel, asegurando alto rendimiento y manejo consistente de filas, columnas y tipos de datos.

¿Por qué debería usar IronXL en lugar de bibliotecas gratuitas como CsvHelper?

Aunque CsvHelper es excelente para operaciones básicas de CSV, IronXL sobresale con características como soporte para libros de trabajo de Excel, rendimiento mejorado y manejo robusto de tipos de datos, haciéndolo adecuado para flujos de trabajo de hojas de cálculo más complejos.

¿Puede IronXL manejar ambos formatos CSV y Excel?

Sí, IronXL está diseñado para manejar eficientemente ambos formatos, CSV y Excel, permitiéndote convertir entre ellos con facilidad.

¿IronXL admite manejo de datos de alto rendimiento?

IronXL está diseñado para alto rendimiento, asegurando procesos suaves de importación y exportación de datos con velocidad y eficiencia óptimas.

¿Es posible integrar IronXL con flujos de trabajo de hojas de cálculo existentes?

Absolutamente, IronXL se integra perfectamente con los flujos de trabajo de hojas de cálculo existentes, mejorando la capacidad de gestionar datos en formatos CSV y Excel.

¿Qué hace que IronXL sea adecuado para operaciones complejas de archivos CSV?

IronXL proporciona características robustas como manejo consistente de filas, columnas y tipos de datos, haciéndolo ideal para operaciones complejas de archivos CSV que requieren más que un manejo básico.

¿Puedo usar IronXL para convertir archivos CSV a Excel?

Sí, una de las características clave de IronXL es su capacidad para convertir archivos CSV a formato Excel y viceversa, racionalizando los procesos de gestión de datos.

¿Cómo asegura IronXL un manejo confiable de archivos CSV?

IronXL asegura un manejo confiable de archivos CSV a través de sus características avanzadas, que incluyen el soporte para tipos de datos complejos y la integración con funcionalidades de Excel.

¿Cuáles son los beneficios de usar IronXL para importación/exportación de datos?

IronXL ofrece procesos suaves de importación/exportación de datos, ahorrando tiempo y esfuerzo a los desarrolladores mientras asegura la integridad y precisión de los datos a través de los formatos.

¿Es fácil de usar IronXL para desarrolladores nuevos en operaciones de CSV en C#?

Sí, IronXL está diseñado con características fáciles de usar y ejemplos de código simples, haciéndolo accesible y fácil de usar para desarrolladores nuevos en operaciones de CSV en C#.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más