跳至页脚内容
使用 IRONXL

如何在 C# 中导入、读取及操作 Excel 数据

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.

常见问题解答

为什么StreamReader不能直接在C#中处理Excel文件?

StreamReader是为文本文件设计的,不支持Excel文件的二进制格式,这就是为什么您使用它读取Excel文档时可能会遇到乱码或异常的原因。相反,建议使用像IronXL这样的库来正确处理Excel文件。

在C#中导入Excel数据的推荐方法是什么?

在C#中导入Excel数据的推荐方法是使用IronXL。它允许开发人员无须Excel Interop即可读取和操作Excel文件,提供了更直接和高效的解决方案。

我可以在C#中不使用Excel Interop操作Excel文件吗?

是的,您可以通过使用IronXL来在C#中操作Excel文件,而无需Excel Interop。它提供了一种在您的C#应用程序中直接处理Excel文档的无缝方式。

使用IronXL处理Excel文件的好处是什么?

IronXL提供了多种好处,包括无需Microsoft Excel即可读写Excel文件,支持多种Excel格式,并且具有简化数据操作任务的强大API。

IronXL是否支持读取具有复杂数据类型的Excel文件?

是的,IronXL支持读取具有复杂数据类型的Excel文件,使您能够在C#应用程序中高效地处理多样的数据结构。

IronXL如何改进在C#中处理Excel文件的过程?

IronXL通过提供一个易于使用的接口来简化处理Excel文件的过程,消除了对Excel Interop的需求,减少了代码的复杂性,并提高了性能。

使用IronXL是否可以以不同格式读写Excel文件?

是的,IronXL支持多种Excel文件格式,如XLSX、XLS、CSV等,使您能够轻松地以各种格式读写文件。

IronXL 能高效处理大型 Excel 文件吗?

IronXL旨在高效处理大型Excel文件,提供强大的性能并在文件操作期间最大限度地减少内存使用。

是什么让IronXL成为C#开发人员处理Excel文件的合适选择?

IronXL是C#开发人员的合适选择,因为它提供了一整套用于轻松读取、写入和操作Excel文件的功能,无需Microsoft Excel或复杂的Interop依赖。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。