Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment importer, lire et manipuler des données Excel en C#

Many C# developers encounter a common challenge when trying to read Excel sheet files: their trusty StreamReader, which works perfectly for text files, fails mysteriously with Excel documents. If you've attempted to read Excel file using StreamReader in C# only to see garbled characters or exceptions, you're not alone. This tutorial explains why StreamReader can't handle Excel files directly and demonstrates the proper solution using IronXL without Excel Interop.

The confusion often arises because CSV files, which Excel can open, work fine with StreamReader. However, true Excel files (XLSX, XLS) require a fundamentally different approach. Understanding this distinction will save you hours of debugging and lead you to the right tool for the job.

How to Import, Read, and Manipulate Excel Data in C#: Image 1 - IronXL

Why Can't StreamReader Read Excel Files?

StreamReader is designed for plain text files, reading character data line by line using a specified encoding. Excel files, despite their spreadsheet appearance, are actually complex binary or ZIP-compressed XML structures that StreamReader cannot interpret.

static void Main(string[] args)
{
 // This code will NOT work - demonstrates the problem
 using (StreamReader reader = new StreamReader("ProductData.xlsx"))
 {
    string content = reader.ReadLine(); // read data
    Console.WriteLine(content); // Outputs garbled binary data
 }
}
static void Main(string[] args)
{
 // This code will NOT work - demonstrates the problem
 using (StreamReader reader = new StreamReader("ProductData.xlsx"))
 {
    string content = reader.ReadLine(); // read data
    Console.WriteLine(content); // Outputs garbled binary data
 }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

When you run this class Program code snippet, instead of seeing your spreadsheet data, you'll encounter binary unknown data, such as "PK♥♦" or similar system characters. This happens because XLSX files are ZIP archives containing multiple XML files, while XLS files use a proprietary binary format. StreamReader expects plain text and tries to interpret these complex structures as characters, resulting in meaningless output.

Sample Input

How to Import, Read, and Manipulate Excel Data in C#: Image 2 - Excel Input

Output

How to Import, Read, and Manipulate Excel Data in C#: Image 3 - Console Output

Modern Excel files (XLSX) contain multiple components: worksheets, styles, shared strings, and relationships, all packaged together. This complexity requires specialized libraries that understand the Excel file structure, which brings us to IronXL.

How to Read Excel Files with IronXL?

IronXL provides a straightforward solution for reading Excel files in C#. Unlike StreamReader, IronXL understands Excel's internal structure and provides intuitive methods to access your data. The library supports Windows, Linux, macOS, and Docker containers, making it ideal for modern, cross-platform applications.

How to Import, Read, and Manipulate Excel Data in C#: Image 4 - Cross Platform

First, install IronXL via NuGet Package Manager:

Install-Package IronXL.Excel

How to Import, Read, and Manipulate Excel Data in C#: Figure 5 - Installation

Here's how to read an Excel file properly:

using IronXL;
// Load the Excel file
WorkBook workbook = WorkBook.Load("sample.xlsx");
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Read specific cell values
string cellValue = worksheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
// Read a range of cells
foreach (var cell in worksheet["A1:C5"])
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}
using IronXL;
// Load the Excel file
WorkBook workbook = WorkBook.Load("sample.xlsx");
WorkSheet worksheet = workbook.DefaultWorkSheet;
// Read specific cell values
string cellValue = worksheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
// Read a range of cells
foreach (var cell in worksheet["A1:C5"])
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code successfully loads your Excel file and provides clean access to cell values. The WorkBook.Load method automatically detects the file format (XLSX, XLS, XLSM, CSV) and handles all the complex parsing internally. You can access cells using familiar Excel notation like "A1" or ranges like "A1:C5", making the code intuitive for anyone familiar with Excel.

How to Read Excel from Memory Streams?

Real-world applications often need to process Excel files from streams rather than disk files. Common scenarios include handling web uploads, retrieving files from databases, or processing data from cloud storage. IronXL handles these situations elegantly:

using IronXL;
using System.IO;
// Read Excel from a memory stream
byte[] fileBytes = File.ReadAllBytes("ProductData.xlsx");
using (MemoryStream stream = new MemoryStream(fileBytes))
{
    WorkBook workbook = WorkBook.FromStream(stream);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    // Process the data
    int rowCount = worksheet.RowCount;
    Console.WriteLine($"The worksheet has {rowCount} rows");
    // Read all data into a new DataTable, return dt
    var dataTable = worksheet.ToDataTable(false);
    // Return DataTable row count 
    Console.WriteLine($"Loaded {dataTable.Rows.Count} data rows");
}
using IronXL;
using System.IO;
// Read Excel from a memory stream
byte[] fileBytes = File.ReadAllBytes("ProductData.xlsx");
using (MemoryStream stream = new MemoryStream(fileBytes))
{
    WorkBook workbook = WorkBook.FromStream(stream);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    // Process the data
    int rowCount = worksheet.RowCount;
    Console.WriteLine($"The worksheet has {rowCount} rows");
    // Read all data into a new DataTable, return dt
    var dataTable = worksheet.ToDataTable(false);
    // Return DataTable row count 
    Console.WriteLine($"Loaded {dataTable.Rows.Count} data rows");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The WorkBook.FromStream method accepts any stream type, whether it's a MemoryStream, FileStream, or network stream. This flexibility allows you to process Excel files from various sources without saving them to disk first. The example also demonstrates converting worksheet data to a DataTable, which integrates seamlessly with databases and data-binding scenarios.

Output

How to Import, Read, and Manipulate Excel Data in C#: Figure 6 - Read Excel from MemoryStream Output

When to use the object sender to read data?

In cases where this code is used within event-driven programming (for example, handling a file upload button in Windows Forms or ASP.NET), the one method signature often includes parameters like object sender and EventArgs e. This context ensures the Excel processing logic ties into UI or service events correctly.

How to Import, Read, and Manipulate Excel Data in C#: Figure 7 - Features

How to Convert Between Excel and CSV?

While StreamReader can handle CSV files, you often need to convert between Excel and CSV formats. IronXL makes this conversion straightforward:

using IronXL;
// Load an Excel file and save as CSV
WorkBook workbook = WorkBook.Load("data.xlsx");
workbook.SaveAsCsv("output.csv");
// Load a CSV file and save as Excel
WorkBook csvWorkbook = WorkBook.LoadCSV("input.csv");
csvWorkbook.SaveAs("output.xlsx");
// Export specific worksheet to CSV
WorkSheet worksheet = workbook.WorkSheets[0];
worksheet.SaveAsCsv("worksheet1.csv");
using IronXL;
// Load an Excel file and save as CSV
WorkBook workbook = WorkBook.Load("data.xlsx");
workbook.SaveAsCsv("output.csv");
// Load a CSV file and save as Excel
WorkBook csvWorkbook = WorkBook.LoadCSV("input.csv");
csvWorkbook.SaveAs("output.xlsx");
// Export specific worksheet to CSV
WorkSheet worksheet = workbook.WorkSheets[0];
worksheet.SaveAsCsv("worksheet1.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These conversions preserve your data while changing the file format. When converting Excel to CSV, IronXL flattens the first worksheet by default, but you can specify which worksheet to export. Converting from CSV to Excel creates a properly formatted spreadsheet that preserves data types and enables future formatting and formula additions.

Conclusion

StreamReader's inability to process Excel files stems from the fundamental difference between plain text and Excel's complex file structure. While StreamReader works perfectly for CSV and other text formats, true Excel files require a specialized library like IronXL that understands the binary and XML structures within.

IronXL provides an elegant solution with its intuitive API, comprehensive format support, and seamless stream processing capabilities. Whether you're building web applications, desktop software, or cloud services, IronXL handles Excel files reliably across all platforms.

How to Import, Read, and Manipulate Excel Data in C#: Figure 8 - Licensing

Ready to start working with Excel files properly? Download IronXL's free trial that best suit your project's needs.

Questions Fréquemment Posées

Pourquoi StreamReader ne peut-il pas gérer les fichiers Excel directement en C#?

StreamReader est conçu pour les fichiers texte et ne prend pas en charge le format binaire des fichiers Excel, c'est pourquoi vous pouvez rencontrer des caractères illisibles ou des exceptions lorsque vous l'utilisez pour lire des documents Excel. À la place, il est recommandé d'utiliser une bibliothèque comme IronXL pour un traitement approprié des fichiers Excel.

Quelle est la méthode recommandée pour importer des données Excel en C#?

La méthode recommandée pour importer des données Excel en C# est d'utiliser IronXL. Cela permet aux développeurs de lire et manipuler des fichiers Excel sans avoir besoin d'Excel Interop, offrant une solution plus simple et plus efficace.

Puis-je manipuler des fichiers Excel en C# sans utiliser Excel Interop?

Oui, vous pouvez manipuler des fichiers Excel en C# sans Excel Interop en utilisant IronXL. Cela offre un moyen facile de travailler avec des documents Excel directement dans votre application C#.

Quels sont les avantages d'utiliser IronXL pour la gestion des fichiers Excel?

IronXL offre plusieurs avantages, notamment la capacité de lire et écrire des fichiers Excel sans avoir besoin de Microsoft Excel, la prise en charge de divers formats Excel, et une API puissante qui simplifie les tâches de manipulation des données.

IronXL prend-il en charge la lecture des fichiers Excel avec des types de données complexes?

Oui, IronXL prend en charge la lecture des fichiers Excel avec des types de données complexes, vous permettant de gérer efficacement des structures de données variées au sein de vos applications C#.

Comment IronXL améliore-t-il le processus de travail avec les fichiers Excel en C#?

IronXL simplifie le processus de travail avec les fichiers Excel en fournissant une interface facile à utiliser qui élimine le besoin d'Excel Interop, réduit la complexité du code et améliore les performances.

Est-il possible de lire et écrire des fichiers Excel dans différents formats en utilisant IronXL?

Oui, IronXL prend en charge plusieurs formats de fichiers Excel tels que XLSX, XLS, CSV, et plus, vous permettant de lire et écrire des fichiers dans divers formats sans effort.

IronXL peut-il gérer de grands fichiers Excel efficacement?

IronXL est conçu pour gérer efficacement les fichiers Excel volumineux, offrant des performances robustes et minimisant l'utilisation de la mémoire lors des opérations sur les fichiers.

Qu'est-ce qui fait de IronXL un choix approprié pour les développeurs C# travaillant avec des fichiers Excel?

IronXL est un choix approprié pour les développeurs C# car il offre un ensemble complet de fonctionnalités pour lire, écrire et manipuler des fichiers Excel avec facilité, sans nécessiter Microsoft Excel ou des dépendances interop complexes.

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