跳至页脚内容
使用 IRONXL

如何在 C# 中使用 IronXL 打开 Excel 文件应用程序

Opening and working with Excel files in C# is something nearly every .NET developer runs into. Whether you’re automating weekly reports, reading data imports, or building tools that generate spreadsheets on the fly, the way you handle Excel files can make a big difference in speed, reliability, and deployment flexibility.

In this tutorial, we’ll look at how to open Excel files in C# using IronXL - a lightweight Excel library that reads, edits, and writes workbooks without needing Microsoft Office installed. You’ll see how simple it is to load data, access worksheets, and work with cells programmatically, all inside your C# application.

Why Choose IronXL Over Microsoft.Office.Interop.Excel?

While Microsoft.Office.Interop.Excel has been the traditional approach for Excel automation, it comes with significant limitations that make IronXL the superior choice for modern applications. Microsoft itself recommends against using Office Interop on servers:

Feature

IronXL

Microsoft.Office.Interop.Excel

Excel Installation Required

✅ No

❌ Yes

Cross-Platform Support

✅ Windows, Linux, macOS

❌ Windows only

Server Deployment

✅ Fully supported

❌ Not recommended by Microsoft

Memory Management

✅ Automatic

❌ Manual COM cleanup required

API Complexity

✅ Simple and intuitive

❌ Complex COM interfaces

File Format Support

✅ XLS, XLSX, CSV, TSV, JSON

⚠️ Limited to Excel formats

IronXL eliminates the dependency on Microsoft Excel, making it ideal for server environments, Docker containers, and cloud platforms like Azure. The library provides a clean, modern API that eliminates the need for dealing with COM objects or manual memory management.

How to Install IronXL for .NET?

Getting started with IronXL is straightforward; it can be added to your project in minutes. Just install it via the NuGet Package Manager:

Install-Package IronXL.Excel

立即开始使用 IronXL。
green arrow pointer

How to Open and Read Excel Files in C#?

Opening existing Excel files with IronXL requires just a few lines of code. The library supports reading various Excel formats, including XLS and XLSX, as seen in the following code snippet:

// Load an existing Excel file
WorkBook workbook = WorkBook.Load("sales-data.xlsx");
// Access the first worksheet
WorkSheet sheet = workbook.WorkSheets[0];
// Or access a worksheet by name
WorkSheet namedSheet = workbook.GetWorkSheet("January Sales");
// Read a specific cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
// Load an existing Excel file
WorkBook workbook = WorkBook.Load("sales-data.xlsx");
// Access the first worksheet
WorkSheet sheet = workbook.WorkSheets[0];
// Or access a worksheet by name
WorkSheet namedSheet = workbook.GetWorkSheet("January Sales");
// Read a specific cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The above code demonstrates loading an Excel file into a WorkBook object, which represents the entire Excel file. The WorkBook.Load() method automatically detects the file format (XLS, XLSX, CSV, or TSV) and handles it appropriately.

You can access worksheets either by index or by name using the GetWorkSheet() method. Individual cell values are accessible through intuitive bracket notation, making the code highly readable. For more complex scenarios, explore working with Excel ranges and cell data formats.

Output

How to Open Excel Files Application in C# Using IronXL: Figure 1 - Opening and reading a sample Excel file

How to Create New Excel Workbooks?

Creating new Excel files is equally simple with IronXL's spreadsheet creation capabilities:

// Create a new workbook
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Author = "Sales Department";
// Create a worksheet
WorkSheet sheet = workbook.CreateWorkSheet("Q1 Report");
// Add data to cells
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Revenue";
sheet["A2"].Value = "Software Licenses";
sheet["B2"].Value = 45000;
// Apply formatting
sheet["B2"].FormatString = "$#,##0.00";
// Save the workbook
workbook.SaveAs("quarterly-report.xlsx");
// Create a new workbook
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Author = "Sales Department";
// Create a worksheet
WorkSheet sheet = workbook.CreateWorkSheet("Q1 Report");
// Add data to cells
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Revenue";
sheet["A2"].Value = "Software Licenses";
sheet["B2"].Value = 45000;
// Apply formatting
sheet["B2"].FormatString = "$#,##0.00";
// Save the workbook
workbook.SaveAs("quarterly-report.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

In this code example, the WorkBook.Create() method initializes a new workbook with your specified format. You can add multiple worksheets using CreateWorkSheet(), populate specific cells in your Excel's rows and columns with various data types, and apply formatting styles. The library automatically handles data type conversion and Excel-specific formatting requirements. Learn more about Excel formulas in C# for advanced calculations.

Output

How to Open Excel Files Application in C# Using IronXL: Figure 2 - Creating new Excel workbooks

How to Read and Process Excel Worksheet Data?

IronXL excels at data extraction and processing:

// Load workbook
WorkBook workbook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Read a range of cells
var range = sheet["A1:D5"];
foreach (var cell in range)
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}
// Convert to DataTable for easier processing
System.Data.DataTable dataTable = sheet.ToDataTable(true);
// Process data using LINQ
decimal total = sheet["C2:C5"].Sum();
Console.WriteLine($"Total: {total}");
// Load workbook
WorkBook workbook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workbook.DefaultWorkSheet;
// Read a range of cells
var range = sheet["A1:D5"];
foreach (var cell in range)
{
    Console.WriteLine($"{cell.AddressString}: {cell.Text}");
}
// Convert to DataTable for easier processing
System.Data.DataTable dataTable = sheet.ToDataTable(true);
// Process data using LINQ
decimal total = sheet["C2:C5"].Sum();
Console.WriteLine($"Total: {total}");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Here, we use the same process to open our Excel file in the project. The range selection syntax (sheet["A1:D5"]) provides an elegant way to work with multiple cells. The ToDataTable() method converts worksheet data into a DataTable, enabling integration with databases and data-binding scenarios. IronXL also supports aggregate functions, such as Sum(), Average(), and Max(), directly on ranges. For handling larger datasets, see the complete API documentation.

How to Open Excel Files Application in C# Using IronXL: Figure 3 - Processed Excel data output

Working Without Microsoft Office

One of IronXL's greatest strengths is its ability to operate independently of Microsoft Office. This capability opens up numerous deployment scenarios:

  • Cloud Deployment: Run on Azure, AWS, or Google Cloud without licensing concerns
  • Docker Containers: Include in containerized applications without complex Office installations
  • Linux Servers: Deploy to cost-effective Linux environments
  • CI/CD Pipelines: Generate Excel reports in automated build processes

The library handles all Excel file generation and manipulation internally, utilizing its own rendering engine to ensure consistent results across all platforms.

Conclusion

IronXL offers a modern and efficient solution for opening and manipulating Excel files in C#. By eliminating Excel dependencies and offering a clean API, it simplifies development while enabling broader deployment options. Whether you're building desktop applications, web services, or cloud-based solutions, IronXL ensures your Excel automation works reliably across all environments.

Ready to modernize your Excel automation? Download IronXL for a free trial starting at $liteLicense.

常见问题解答

如何在 C# 中打开 Excel 文件而无需 Microsoft Office?

您可以使用 IronXL 在 C# 中打开 Excel 文件,而无需 Microsoft Office。IronXL 提供了一个优于 Interop 的现代替代方案,具有更好的性能且无 Excel 依赖。

使用 IronXL 处理 C# 中的 Excel 文件有哪些好处?

IronXL 提供了多项好处,包括提高性能,无需依赖 Excel 安装,且在部署方面具有更大的灵活性。它允许开发者高效地自动生成报告、读取数据导入和生成电子表格。

IronXL 能处理 Excel 文件的自动化任务吗?

可以,IronXL 非常适合用于生成每周报告、读取数据导入和创建动态电子表格生成工具等自动化任务。

IronXL 是 C# 应用程序中 Interop 的适合替代品吗?

IronXL 是 Interop 的适当替代品,提供了一种现代解决方案,无需 Excel 依赖,并在处理 Excel 文件时提高了应用性能。

IronXL 支持读取和写入 Excel 文件吗?

IronXL 完全支持读取和写入 Excel 文件,成为 .NET 开发者处理电子表格数据的多功能工具。

Curtis Chau
技术作家

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

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