使用 IRONXL 如何在 C# 使用 StreamReader 读取 Excel 文件 Curtis Chau 已发布:十月 19, 2025 Download IronXL NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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. 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 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. First, install IronXL via NuGet Package Manager: Install-Package IronXL.Excel 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 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 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. 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文件的二进制格式的能力,这导致乱码或异常。 什么是 IronXL? IronXL是一个C#库,允许开发人员在不需要Excel Interop的情况下读取、写入和操作Excel文件,提供了更高效和可靠的解决方案。 IronXL如何改善C#中Excel文件的读取? IronXL通过提供访问Excel数据的方法简化了读取Excel文件的过程,而无需复杂的Interop代码或处理文件格式的复杂性。 我可以用IronXL读取未安装Excel的Excel文件吗? 可以,IronXL不需要在系统中安装Microsoft Excel,是处理C#中Excel文件的独立解决方案。 使用 IronXL 比使用 Excel Interop 有什么好处? IronXL更快,消除了安装Excel的需要,并减少了常见于Excel Interop的版本兼容性问题的风险。 IronXL 适合大型 Excel 文件吗? 是的,IronXL经过性能优化,可以有效处理大型Excel文件,适用于处理大量数据的应用。 IronXL支持同时读取.xls和.xlsx格式吗? IronXL支持.xls和.xlsx格式,允许开发人员无缝处理各种Excel文件类型。 如何在我的C#项目中开始使用IronXL? 您可以通过Visual Studio中的NuGet包管理器安装IronXL,并将其集成到您的C#项目中以读取和操作Excel文件。 IronXL常见的使用案例是什么? IronXL的常见使用案例包括从Excel文件中提取数据、生成报告、数据操作以及在C#应用程序中自动化与Excel相关的任务。 IronXL可以用于Web应用程序吗? 可以,IronXL可以在桌面和Web应用程序中使用,为您在项目中实现Excel处理功能提供灵活性。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十月 27, 2025 如何在 C# 中创建 Excel 数据透视表 学习通过这个清晰的分步指南使用C# Interop和IronXL在Excel中创建数据透视表。 阅读更多 已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多 已发布十月 27, 2025 如何在.NET Core中使用CSV Reader与IronXL 学习通过实际示例有效地使用IronXL作为.NET Core的CSV读取器。 阅读更多 如何在 C# 中导入、读取及操作 Excel 数据如何在 C# 中使用 IronXL 读...
已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多