Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment utiliser une bibliothèque CSV C# pour lire et écrire des fichiers

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

Commencez avec IronXL maintenant.
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.

Questions Fréquemment Posées

Qu'est-ce qu'IronXL et comment aide-t-il avec les fichiers CSV en C# ?

IronXL est une bibliothèque C# puissante qui permet aux développeurs de lire, écrire et convertir des fichiers CSV de manière fluide. Elle offre un support étendu aux classeurs Excel, garantissant des performances élevées et une gestion cohérente des lignes, colonnes et types de données.

Pourquoi devrais-je utiliser IronXL plutôt que des bibliothèques gratuites comme CsvHelper ?

Bien que CsvHelper soit excellent pour les opérations CSV de base, IronXL excelle avec des fonctionnalités telles que la prise en charge des classeurs Excel, une performance améliorée et une gestion robuste des types de données, la rendant adaptée à des flux de travail de feuilles de calcul plus complexes.

IronXL peut-il gérer à la fois les formats CSV et Excel ?

Oui, IronXL est conçu pour gérer efficacement les formats CSV et Excel, vous permettant de convertir facilement entre les deux.

IronXL supporte-t-il une gestion des données haute performance ?

IronXL est conçu pour des performances élevées, assurant des processus d'importation et d'exportation de données fluides avec une vitesse et une efficacité optimales.

Est-il possible d'intégrer IronXL avec les flux de travail de feuilles de calcul existants ?

Absolument, IronXL s'intègre parfaitement avec les flux de travail de feuilles de calcul existants, améliorant la capacité à gérer les données à travers les formats CSV et Excel.

Qu'est-ce qui rend IronXL adapté aux opérations complexes de fichiers CSV ?

IronXL fournit des fonctionnalités robustes telles qu'une gestion cohérente des lignes, colonnes et types de données, le rendant idéal pour les opérations complexes de fichiers CSV qui nécessitent plus qu'une gestion de base.

Puis-je utiliser IronXL pour convertir des fichiers CSV en Excel ?

Oui, l'une des principales fonctionnalités d'IronXL est sa capacité à convertir des fichiers CSV en format Excel et vice versa, rationalisant ainsi les processus de gestion de données.

Comment IronXL assure-t-il une gestion fiable des fichiers CSV ?

IronXL assure une gestion fiable des fichiers CSV grâce à ses fonctionnalités avancées qui incluent le support des types de données complexes et l'intégration avec les fonctionnalités Excel.

Quels sont les avantages d'utiliser IronXL pour l'importation/exportation de données ?

IronXL offre des processus d'importation/exportation de données fluides, économisant aux développeurs du temps et des efforts tout en garantissant l'intégrité et l'exactitude des données à travers les formats.

IronXL est-il facile à utiliser pour les développeurs novices en opérations CSV en C# ?

Oui, IronXL est conçu avec des fonctionnalités conviviales et des exemples de code simples, le rendant accessible et facile à utiliser pour les développeurs novices en opérations CSV en C#.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite