
如何在 C# 中打开 Excel 文件
IronXL使 C# 开发人员无需安装 Microsoft Office 即可打开、读取和操作 Excel 文件。 只需使用sheet["A1"]读取单元格值。
本教程探讨了如何在 C# 项目中使用IronXL打开和读取 Excel 文件,为初级开发人员提供处理 Excel 数据的全面示例和最佳实践。
IronXL Excel Library是什么?
IronXL是一个.NET库,它优先考虑易用性、准确性和速度。 它可以帮助您高效地打开、读取、创建和编辑Excel 文件,而无需 MS Office Interop,因此对于希望在 C# 中使用 Excel 而无需 Interop 的开发人员来说,这是一个实用的选择。
IronXL与所有.NET Framework 以及Linux 、 macOS 、 Docker 、 Azure和AWS兼容。 您可以使用它来创建控制台应用程序、Web 应用程序和桌面应用程序,例如Blazor和.NET MAUI,用于开发现代 Web 应用程序。它支持不同的工作簿格式,例如 XLS 和 XLSX 文件、XSLT 和 XLSM、CSV 和 TSV。
IronXL的主要特点是什么?
- 使用LoadSpreadsheets打开、读取和搜索 XLS/XLSX/CSV/TSV 格式的数据。
- 使用"保存并导出"功能将 Excel 工作表导出为多种格式。
- 使用安全功能对文件进行加密和解密,并设置密码。
- 通过DataSet集成,将Excel表处理为
DataTable对象。 - Excel公式自动重新计算,支持数学函数。
- 使用直观的范围语法如
WorkSheet["A1:B10"]编辑电子表格数据。 -对单元格区域、列和行进行排序。 - 设置单元格样式,包括字体、背景、边框、对齐方式和数字格式。
如何在C#中打开Excel文件?
开始之前我需要准备什么?
要在 C# 应用程序中使用 IronXL,请在本地计算机上安装以下组件:
- Visual Studio - 用于开发 C# .NET应用程序的官方 IDE。 您可以从微软网站下载并安装 Visual Studio。 您也可以使用**
JetBrainsReSharper& Rider**。 有关更多设置指导,请参阅入门概述。 - IronXL - 帮助在 C# 中处理 Excel 表格的 Excel 库。 必须先将其安装到您的 C# 应用程序中才能使用。 您可以从NuGet网站下载,也可以从 Visual Studio 中的"管理NuGet程序包"下载。 您也可以直接下载.NET Excel DLL文件。 有关许可实施,请参阅"使用许可证密钥" 。
我应该导入哪些命名空间?
安装好 Visual Studio 和 IronXL 后,在 C# 文件顶部添加以下代码行,以添加必要的 IronXL 命名空间:
// Add reference to the IronXL library
using IronXL;' Add reference to the IronXL library
Imports IronXL要使用特定的 Excel 格式或高级功能,您可能还需要:
using IronXL.Formatting; // For cell styling
using IronXL.Drawing; // For images and charts
using System.Data; // For DataSet/DataTable operationsImports IronXL.Formatting ' For cell styling
Imports IronXL.Drawing ' For images and charts
Imports System.Data ' For DataSet/DataTable operations如何加载现有的Excel文件?
Excel 文件(也称为工作簿)由多个工作表组成,每个工作表都包含单元格值。 要打开和读取Excel文件,请使用WorkBook类的Load方法加载。 LoadSpreadsheets功能支持多种格式。
// Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
// You can also load from streams for web applications
// using (var stream = File.OpenRead("test.xlsx"))
// {
// WorkBook workbook = WorkBook.Load(stream);
// }' Supported Excel spreadsheet formats for reading include: XLSX, XLS, CSV, and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
' You can also load from streams for web applications
' Using stream = File.OpenRead("test.xlsx")
' Dim workbook As WorkBook = WorkBook.Load(stream)
' End Using这将工作簿初始化为WorkBook实例。 要打开特定的WorkSheets集合中检索。 《管理工作表》指南提供了有关工作表操作的更多详细信息:
// Access the first worksheet in the workbook
WorkSheet sheet = workbook.WorkSheets.First();
// Alternative ways to access worksheets
WorkSheet sheetByIndex = workbook.WorkSheets[0]; // By index
WorkSheet sheetByName = workbook.GetWorkSheet("Sheet1"); // By name' Access the first worksheet in the workbook
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Alternative ways to access worksheets
Dim sheetByIndex As WorkSheet = workbook.WorkSheets(0) ' By index
Dim sheetByName As WorkSheet = workbook.GetWorkSheet("Sheet1") ' By name这将访问 Excel 文件中的第一个工作表,以便进行读取和写入操作。
Excel 文件
如何读取Excel单元格中的数据?
Excel 文件打开后,即可读取数据。 使用 IronXL 在 C# 中读取 Excel 文件中的数据非常简单。 您可以使用"选择范围"功能指定单元格引用来读取单元格值。
以下代码用于获取单元格的值:
// Select the cell using Excel notation and retrieve its integer value
int cellValue = sheet["C2"].IntValue;
// You can also retrieve values in different formats
string textValue = sheet["C2"].StringValue;
decimal decimalValue = sheet["C2"].DecimalValue;
DateTime dateValue = sheet["C2"].DateTimeValue;
bool boolValue = sheet["C2"].BoolValue;
// Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}");
// Check if cell is empty before reading
if (!sheet["C2"].IsEmpty)
{
Console.WriteLine($"Cell value: {sheet["C2"].Value}");
}' Select the cell using Excel notation and retrieve its integer value
Dim cellValue As Integer = sheet("C2").IntValue
' You can also retrieve values in different formats
Dim textValue As String = sheet("C2").StringValue
Dim decimalValue As Decimal = sheet("C2").DecimalValue
Dim dateValue As DateTime = sheet("C2").DateTimeValue
Dim boolValue As Boolean = sheet("C2").BoolValue
' Display the value in the console
Console.WriteLine($"Cell C2 contains: {cellValue}")
' Check if cell is empty before reading
If Not sheet("C2").IsEmpty Then
Console.WriteLine($"Cell value: {sheet("C2").Value}")
End If译文如下:
读取 Excel
要从一系列单元格中读取数据,请使用循环遍历指定的范围。 "选择 Excel 区域"示例提供了更多模式:
// Iterate through a range of cells and display their address and text content
foreach (var cell in sheet["A2:A6"])
{
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read an entire column
foreach (var cell in sheet.GetColumn(0)) // Column A
{
if (!cell.IsEmpty)
{
Console.WriteLine($"Column A value: {cell.Text}");
}
}
// Read an entire row
foreach (var cell in sheet.GetRow(1)) // Row 2
{
Console.WriteLine($"Row 2 value: {cell.Text}");
}' Iterate through a range of cells and display their address and text content
For Each cell In sheet("A2:A6")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next
' Read an entire column
For Each cell In sheet.GetColumn(0) ' Column A
If Not cell.IsEmpty Then
Console.WriteLine($"Column A value: {cell.Text}")
End If
Next
' Read an entire row
For Each cell In sheet.GetRow(1) ' Row 2
Console.WriteLine($"Row 2 value: {cell.Text}")
Next单元格范围A2:A6中的每个值都被访问并打印到控制台。
读取单元格范围
有关更详细的读写示例,请查看C# 中的 Excel 读取教程。 您还可以将 Excel 数据转换为数据表,以便更轻松地进行操作:
// Convert worksheet to DataTable for easier data manipulation
DataTable dataTable = sheet.ToDataTable(true); // true = first row contains headers
// Access data using DataTable methods
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"Employee: {row["Name"]}, Salary: {row["Salary"]}");
}' Convert worksheet to DataTable for easier data manipulation
Dim dataTable As DataTable = sheet.ToDataTable(True) ' True = first row contains headers
' Access data using DataTable methods
For Each row As DataRow In dataTable.Rows
Console.WriteLine($"Employee: {row("Name")}, Salary: {row("Salary")}")
Next如何创建新的Excel文件?
IronXL还方便创建新的工作簿以保存和检索数据。 《创建电子表格》指南提供了全面的示例。
只需一行代码即可创建一个新的 Excel 文件:
// Create a new workbook with the XLSX format
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
// Alternative: Create with XLS format for compatibility
WorkBook xlsWorkBook = new WorkBook(ExcelFileFormat.XLS);
// Set workbook metadata
workBook.Metadata.Title = "Employee Data";
workBook.Metadata.Author = "Your Name";
workBook.Metadata.Keywords = "employees, salary, data";' Create a new workbook with the XLSX format
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)
' Alternative: Create with XLS format for compatibility
Dim xlsWorkBook As New WorkBook(ExcelFileFormat.XLS)
' Set workbook metadata
workBook.Metadata.Title = "Employee Data"
workBook.Metadata.Author = "Your Name"
workBook.Metadata.Keywords = "employees, salary, data"接下来,创建一个工作表并向其中添加数据。 有关更高级的创建模式,请参阅创建新的 Excel 文件。
如何向工作簿中添加工作表?
// Create a worksheet named "GDPByCountry" in the workbook
WorkSheet workSheet = workBook.CreateWorkSheet("GDPByCountry");
// Create multiple worksheets at once
WorkSheet sheet2 = workBook.CreateWorkSheet("PopulationData");
WorkSheet sheet3 = workBook.CreateWorkSheet("Summary");
// Copy an existing worksheet
WorkSheet copiedSheet = workSheet.CopySheet("GDPByCountryCopy");' Create a worksheet named "GDPByCountry" in the workbook
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("GDPByCountry")
' Create multiple worksheets at once
Dim sheet2 As WorkSheet = workBook.CreateWorkSheet("PopulationData")
Dim sheet3 As WorkSheet = workBook.CreateWorkSheet("Summary")
' Copy an existing worksheet
Dim copiedSheet As WorkSheet = workSheet.CopySheet("GDPByCountryCopy")这段代码会在工作簿中添加一个名为"GDPByCountry"的工作表,允许您添加单元格值。 了解更多关于管理工作表和复制工作表的信息。
要为特定单元格设置值,请使用以下代码:
// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";
// Add different types of data
workSheet["A2"].Value = 12345; // Integer
workSheet["A3"].Value = 99.99m; // Decimal
workSheet["A4"].Value = DateTime.Now; // Date
workSheet["A5"].Value = true; // Boolean
// Add formulas
workSheet["B1"].Formula = "=SUM(A2:A3)";
// Set multiple cells at once using a range
workSheet["C1:C5"].Value = "Bulk Value";
// Save the workbook
workBook.SaveAs("output.xlsx");' Set the value of cell A1 to "Example"
workSheet("A1").Value = "Example"
' Add different types of data
workSheet("A2").Value = 12345 ' Integer
workSheet("A3").Value = 99.99D ' Decimal
workSheet("A4").Value = DateTime.Now ' Date
workSheet("A5").Value = True ' Boolean
' Add formulas
workSheet("B1").Formula = "=SUM(A2:A3)"
' Set multiple cells at once using a range
workSheet("C1:C5").Value = "Bulk Value"
' Save the workbook
workBook.SaveAs("output.xlsx")最终输出结果为:
向单元格添加值
使用不同的Excel格式
IronXL支持多种 Excel 格式。 以下是如何处理不同文件类型的方法:
// Convert between formats
WorkBook workbook = WorkBook.Load("data.csv");
workbook.SaveAs("data.xlsx"); // Convert CSV to XLSX
// Export to different formats
workbook.SaveAsCsv("output.csv", ";"); // CSV with semicolon delimiter
workbook.SaveAsJson("output.json"); // Export as JSON
workbook.SaveAsXml("output.xml"); // Export as XML' Convert between formats
Dim workbook As WorkBook = WorkBook.Load("data.csv")
workbook.SaveAs("data.xlsx") ' Convert CSV to XLSX
' Export to different formats
workbook.SaveAsCsv("output.csv", ";") ' CSV with semicolon delimiter
workbook.SaveAsJson("output.json") ' Export as JSON
workbook.SaveAsXml("output.xml") ' Export as XML了解更多关于转换电子表格文件类型以及如何将 XLSX 转换为 CSV、JSON、XML 的信息。
错误处理和最佳实践
处理Excel文件时,要实施适当的错误处理:
try
{
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
// Check if sheet exists
if (sheet == null)
{
Console.WriteLine("Worksheet not found!");
return;
}
// Process data
var value = sheet["A1"].Value;
}
catch (Exception ex)
{
Console.WriteLine($"Error reading Excel file: {ex.Message}");
}Try
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet1")
' Check if sheet exists
If sheet Is Nothing Then
Console.WriteLine("Worksheet not found!")
Return
End If
' Process data
Dim value = sheet("A1").Value
Catch ex As Exception
Console.WriteLine($"Error reading Excel file: {ex.Message}")
End Try我们学到了什么?
本文演示了如何使用 IronXL 在 C# 中打开和读取 Excel 文件,例如 XLS 和 XLSX 文件。 IronXL不需要在系统上安装 Microsoft Excel 即可执行与 Excel 相关的任务,因此非常适合Docker 部署和Azure Functions。
IronXL提供了一个全面的 Excel 相关任务编程解决方案,包括公式计算、字符串排序、修剪、查找和替换、合并和取消合并、保存文件等等。 您还可以设置单元格数据格式、使用条件格式以及 创建图表。
要了解高级功能,请探索分组和取消分组、命名区域、超链接以及保护 Excel 文件。 完整的API 参考文档提供了所有功能的详细文档。
IronXL提供30 天免费试用,并可授权用于商业用途。 IronXL的Lite套餐从$999起。 如需更多资源,请访问教程部分或浏览常见场景的代码示例。

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



