跳至页脚内容
使用 IRONXL

如何在 C# 中处理 Excel 文件

Working with Microsoft Excel files in programming languages has become a significant requirement in today's modern programming paradigm. Excel generation is required for automation, data analysis, measuring productivity, reports, etc. IronXL from Iron Software is a powerful C# library that allows developers to read, write, and manipulate Excel documents without needing Microsoft Excel installed on the machine in any application like web services, console, desktop, etc. This makes it an excellent choice for applications that need to handle Excel data efficiently and effectively. In this article, we’ll explore how to use IronXL to work with Excel files in C#.

How to work with Excel workbook in C#

  1. Create a Visual Studio project and add the IronXL NuGet package.
  2. Create an Excel file without Interop.
  3. Add Style to Excel file using IronXL.
  4. Read values from Excel and calculate.
  5. Convert Excel to HTML for web usage.

Introducing IronXL Library

IronXL is a robust library for .NET that simplifies working with Excel files. IronXL is a powerful .NET library designed for creating, reading, and editing Excel files effortlessly. It features an intuitive API that simplifies working with Excel documents, supporting various formats like XLS, XLSX, and CSV. This versatility allows for easy manipulation of cell values, formulas, and formatting. IronXL is optimized for performance, and capable of efficiently handling large files and complex data operations while ensuring efficient memory usage. Its cross-platform compatibility enhances its utility, making IronXL an invaluable tool for developers across different operating systems. Here are some of its key features and benefits:

Key Features

  1. Import and Export:

    • Import Data: Supports XLS, XLSX, CSV, and TSV formats.
    • Export Data: Can export worksheets to XLS, XLSX, CSV, TSV, and JSON formats.
  2. Data Manipulation:

    • System.Data Integration: Work with spreadsheets as System.Data.DataSet and System.Data.DataTable objects.
    • Formulas: Supports Excel formulas, which are recalculated every time a sheet is edited.
  3. Styling and Formatting:

    • Cell Styling: Customize font, size, background pattern, border, alignment, and number formats.
    • Ranges: Intuitive range setting with WorkSheet["A1:B10"] syntax.
  4. Security:

    • Encryption: Encrypt and decrypt XLSX, XLSM, and XLTX files with passwords.
  5. Cross Platform Compatibility:
    • Works with .NET Framework, .NET Core, .NET Standard, and Azure.
    • Compatible with Windows, macOS, Linux, Docker, Azure, and AWS.

Benefits

  1. No Need for Microsoft Office: IronXL does not require Microsoft Office to be installed, making it lightweight and easy to deploy.
  2. Ease of Use: The API is intuitive and easy to use, allowing developers to quickly integrate Excel functionality into their applications.
  3. Performance: IronXL is optimized for performance, ensuring fast and efficient processing of large Excel files.
  4. Versatility: Suitable for a wide range of applications, including web, desktop, and cloud-based solutions.
  5. Comprehensive Documentation: Extensive documentation and examples are available, making it easier for developers to get started and find solutions to common problems.

Getting Started

To use IronXL in your .NET projects, you need to ensure that your development environment meets the following prerequisites:

Prerequisites

  1. .NET Framework: IronXL supports .NET Framework 4.5 and above .NET technologies.
  2. .NET Core and .NET Standard: Compatible with .NET Core 2, 3, 5, 6, 7, 8 and 9. Supports .NET Standard 2.0 and 2.1.
  3. Operating Systems: Works on Windows, macOS, and Linux. Compatible with Docker, Azure, and AWS environments.
  4. No Need for Microsoft Office: IronXL does not require Microsoft Office or Excel Interop to be installed.
  5. Code editor: Any visual C# code editor like Visual Studio etc.

Installation

You can install IronXL via NuGet Package Manager in Visual Studio or using the Package Manager Console with the following command:

dotnet add package IronXL.Excel --version 2024.8.5
dotnet add package IronXL.Excel --version 2024.8.5
SHELL

How to work with Excel workbook in C#

To get started with working on an Excel file, first, let's develop a Visual Studio project and add the IronXL library.

Step 1: Create a Visual Studio Project and Add IronXL NuGet Package

Open Microsoft Visual Studio and select the 'Create a new project' option to get started with creating the project.

How to Work with Excel Files in C#: Figure 1 - New Project

Select the project template of your choice, here we have selected the Console application for simplicity.

How to Work with Excel Files in C#: Figure 2 - Console App

Now enter the project name and location for the project.

How to Work with Excel Files in C#: Figure 3 - Project Configuration

Select the .NET Framework version you prefer. We have selected the latest one available on our machine.

How to Work with Excel Files in C#: Figure 4 - Target Framework

Once the Create button is clicked, the project will be created and ready for use. Open Solution Explorer to check the project files.

How to Work with Excel Files in C#: Figure 5 - Solution Explorer

Now, let's install the IronXL library from the NuGet package manager as shown above.

Step 2: Create an Excel file without Interop

Now, let's create an Excel file without using the Microsoft Interop library.

using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create new Excel WorkBook Object
            WorkBook workBook = WorkBook.Create();
            // Create WorkSheet
            WorkSheet workSheet = workBook.CreateWorkSheet("newXlDemo");
            // Add data in new worksheet
            workSheet["A1"].Value = "IronXL is the best Excel library";           
            // Save the Excel file as XLSX
            workBook.SaveAs("myIronXlDemo.xlsx");
        }
    }
}
using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create new Excel WorkBook Object
            WorkBook workBook = WorkBook.Create();
            // Create WorkSheet
            WorkSheet workSheet = workBook.CreateWorkSheet("newXlDemo");
            // Add data in new worksheet
            workSheet["A1"].Value = "IronXL is the best Excel library";           
            // Save the Excel file as XLSX
            workBook.SaveAs("myIronXlDemo.xlsx");
        }
    }
}
Imports IronXL

Namespace WorkingWithIronXL
	Public Class Program
		Public Shared Sub Main()
			' Create new Excel WorkBook Object
			Dim workBook As WorkBook = WorkBook.Create()
			' Create WorkSheet
			Dim workSheet As WorkSheet = workBook.CreateWorkSheet("newXlDemo")
			' Add data in new worksheet
			workSheet("A1").Value = "IronXL is the best Excel library"
			' Save the Excel file as XLSX
			workBook.SaveAs("myIronXlDemo.xlsx")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. We add the IronXL namespace to start working with the library.
  2. Then we create an Excel object to create an XLSX file with WorkBook.Create().
  3. The CreateWorkSheet method is then called to create a worksheet inside the workbook.
  4. Add values to a cell using workSheet["A1"].Value.
  5. Then save the Excel file using workBook.SaveAs by providing a name for the file.

Output Excel file

How to Work with Excel Files in C#: Figure 6 - Excel Output

Step 3: Add Style to the Excel file using IronXL

Now let's see how to add styles to Excel cells.

using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create a new workbook
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Create a new worksheet
            WorkSheet workSheet = workBook.CreateWorkSheet("StyledSheet");
            // Add multiple values to cells
            workSheet["A1"].Value = "This Styled Text with Awesome IronXL library";
            workSheet["A2"].Value = 999999;
            // Apply styles to cells
            workSheet["A1"].Style.Font.Bold = true;
            workSheet["A1"].Style.Font.Italic = true;
            workSheet["A1"].Style.Font.Height = 14;
            workSheet["A1"].Style.Font.Color = "#FF0000"; // Red color
            workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
            workSheet["A2"].Style.BottomBorder.SetColor("#00FF00"); // Green color
            // Save the workbook
            workBook.SaveAs("myIronXlWriteDemo.xlsx");
        }
    }
}
using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create a new workbook
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Create a new worksheet
            WorkSheet workSheet = workBook.CreateWorkSheet("StyledSheet");
            // Add multiple values to cells
            workSheet["A1"].Value = "This Styled Text with Awesome IronXL library";
            workSheet["A2"].Value = 999999;
            // Apply styles to cells
            workSheet["A1"].Style.Font.Bold = true;
            workSheet["A1"].Style.Font.Italic = true;
            workSheet["A1"].Style.Font.Height = 14;
            workSheet["A1"].Style.Font.Color = "#FF0000"; // Red color
            workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
            workSheet["A2"].Style.BottomBorder.SetColor("#00FF00"); // Green color
            // Save the workbook
            workBook.SaveAs("myIronXlWriteDemo.xlsx");
        }
    }
}
Imports IronXL

Namespace WorkingWithIronXL
	Public Class Program
		Public Shared Sub Main()
			' Create a new workbook
			Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
			' Create a new worksheet
			Dim workSheet As WorkSheet = workBook.CreateWorkSheet("StyledSheet")
			' Add multiple values to cells
			workSheet("A1").Value = "This Styled Text with Awesome IronXL library"
			workSheet("A2").Value = 999999
			' Apply styles to cells
			workSheet("A1").Style.Font.Bold = True
			workSheet("A1").Style.Font.Italic = True
			workSheet("A1").Style.Font.Height = 14
			workSheet("A1").Style.Font.Color = "#FF0000" ' Red color
			workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double
			workSheet("A2").Style.BottomBorder.SetColor("#00FF00") ' Green color
			' Save the workbook
			workBook.SaveAs("myIronXlWriteDemo.xlsx")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. Create an Excel file using WorkBook.Create.
  2. Create a worksheet using workBook.CreateWorkSheet.
  3. Add values to cells using workSheet["A1"].Value.
  4. Add styles to each cell using the properties on the cell like workSheet["A1"].Style.Font.Bold.
  5. Save the workbook using workBook.SaveAs.

Output Excel File

How to Work with Excel Files in C#: Figure 7 - Styled Excel Output

Step 4: Read Values from Excel and calculate

Now that we have seen how to create Excel files, let's see the following code on how we can read Excel files using IronXL and perform some in-memory calculations.

using IronXL;
using System;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ReadData()
        {
            // Load the Excel worksheet
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            // Select the first worksheet
            WorkSheet workSheet = workBook.WorkSheets[0];
            // Read a specific cell value
            int cellValue = workSheet["A2"].IntValue;
            Console.WriteLine($"Value in A2: {cellValue}");
            // Read a range of cells
            foreach (var cell in workSheet["A1:H10"])
            {
                Console.Write($"{cell.Text}\t");
                if(cell.AddressString.Contains("H"))
                {
                    Console.WriteLine();
                }
            }
            // Calculate aggregate values
            decimal sum = workSheet["F2:F10"].Sum();
            Console.WriteLine($"Sum of F2:F10: {sum}");
        }
    }
}
using IronXL;
using System;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ReadData()
        {
            // Load the Excel worksheet
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            // Select the first worksheet
            WorkSheet workSheet = workBook.WorkSheets[0];
            // Read a specific cell value
            int cellValue = workSheet["A2"].IntValue;
            Console.WriteLine($"Value in A2: {cellValue}");
            // Read a range of cells
            foreach (var cell in workSheet["A1:H10"])
            {
                Console.Write($"{cell.Text}\t");
                if(cell.AddressString.Contains("H"))
                {
                    Console.WriteLine();
                }
            }
            // Calculate aggregate values
            decimal sum = workSheet["F2:F10"].Sum();
            Console.WriteLine($"Sum of F2:F10: {sum}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronXL
Imports System

Namespace WorkingWithIronXL
	Friend Class IronXlDemo
		Public Shared Sub ReadData()
			' Load the Excel worksheet
			Dim workBook As WorkBook = WorkBook.Load("sampleEmployeeData.xlsx")
			' Select the first worksheet
			Dim workSheet As WorkSheet = workBook.WorkSheets(0)
			' Read a specific cell value
			Dim cellValue As Integer = workSheet("A2").IntValue
			Console.WriteLine($"Value in A2: {cellValue}")
			' Read a range of cells
			For Each cell In workSheet("A1:H10")
				Console.Write($"{cell.Text}" & vbTab)
				If cell.AddressString.Contains("H") Then
					Console.WriteLine()
				End If
			Next cell
			' Calculate aggregate values
			Dim sum As Decimal = workSheet("F2:F10").Sum()
			Console.WriteLine($"Sum of F2:F10: {sum}")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. We load a sample Excel file into memory using WorkBook.Load.
  2. Access the first worksheet in the workbook.
  3. Read a specific cell's value and display it using Console.WriteLine.
  4. Iterate through a range of cells and print out each value. Lines are printed for every end of column 'H'.
  5. Calculate the sum of values in the range F2-F10 and print it.

Input Excel

How to Work with Excel Files in C#: Figure 8 - Excel Input

Output

How to Work with Excel Files in C#: Figure 9 - Console Output

Step 5: Convert Excel to HTML for web usage

Now that we know how to generate, read, and write Excel files let us see how to convert Excel to HTML for web usage.

using IronXL;
using IronXL.Options;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ConvertToHtml()
        {
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            var options = new HtmlExportOptions()
            {
                // Set row/column numbers visible in HTML document
                OutputRowNumbers = true,
                OutputColumnHeaders = true,
                // Set hidden rows/columns visible in HTML document
                OutputHiddenRows = true,
                OutputHiddenColumns = true,
                // Set leading spaces as non-breaking
                OutputLeadingSpacesAsNonBreaking = true
            };
            // Export workbook to the HTML file
            workBook.ExportToHtml("workBook.html", options);
        }
    }
}
using IronXL;
using IronXL.Options;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ConvertToHtml()
        {
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            var options = new HtmlExportOptions()
            {
                // Set row/column numbers visible in HTML document
                OutputRowNumbers = true,
                OutputColumnHeaders = true,
                // Set hidden rows/columns visible in HTML document
                OutputHiddenRows = true,
                OutputHiddenColumns = true,
                // Set leading spaces as non-breaking
                OutputLeadingSpacesAsNonBreaking = true
            };
            // Export workbook to the HTML file
            workBook.ExportToHtml("workBook.html", options);
        }
    }
}
Imports IronXL
Imports IronXL.Options

Namespace WorkingWithIronXL
	Friend Class IronXlDemo
		Public Shared Sub ConvertToHtml()
			Dim workBook As WorkBook = WorkBook.Load("sampleEmployeeData.xlsx")
			Dim options = New HtmlExportOptions() With {
				.OutputRowNumbers = True,
				.OutputColumnHeaders = True,
				.OutputHiddenRows = True,
				.OutputHiddenColumns = True,
				.OutputLeadingSpacesAsNonBreaking = True
			}
			' Export workbook to the HTML file
			workBook.ExportToHtml("workBook.html", options)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. Load the Excel file "sampleEmployeeData.xlsx" using the Load method.
  2. Set the options for converting to HTML using HtmlExportOptions.
  3. Use the ExportToHtml method to convert and save the workbook as an HTML file.

Input

How to Work with Excel Files in C#: Figure 10 - Excel Input for Web

Output

How to Work with Excel Files in C#: Figure 11 - HTML Output

Real-World Use Cases

IronXL is a versatile .NET library with a wide range of real-world applications, including:

1. Business Reporting:

  • Automating the generation of periodic reports, such as sales summaries, financial statements, and performance metrics.
  • Creating custom dashboards that pull data from various sources and present it in an Excel format.

2. Data Analysis:

  • Processing large datasets to perform statistical analysis, data cleaning, and data transformation.
  • Exporting analyzed data into Excel for further examination and sharing with stakeholders.

3. Inventory Management:

  • Managing product inventories by creating and updating Excel sheets with stock levels, supplier details, and reorder points.
  • Generating inventory reports to track stock movement and identify trends.

4. Customer Relationship Management (CRM):

  • Exporting customer data from CRM systems into Excel for detailed analysis and reporting.
  • Updating CRM records by importing modified data from Excel files.

5. Educational Institutions:

  • Creating and maintaining student grade books, attendance records, and progress reports.
  • Generating exam results and detailed performance analysis for teachers and students.

6. Financial Services:

  • Automating the creation of financial models, budgets, and forecasts in Excel.
  • Consolidating financial data from multiple sources for comprehensive financial reporting.

7. Human Resources:

  • Managing employee data, including contact details, payroll information, and performance evaluations.
  • Generating reports on HR metrics such as headcount, turnover rates, and employee demographics.

8. Project Management:

  • Tracking project timelines, milestones, and resource allocation using Excel sheets.
  • Creating Gantt charts and other project management tools directly within Excel.

9. E-commerce:

  • Exporting order details, customer information, and sales data from e-commerce platforms to Excel.
  • Analyzing sales trends, customer behavior, and product performance.

10. Healthcare:

  • Managing patient records, appointment schedules, and treatment plans in Excel.
  • Analyzing healthcare data to identify patterns and improve patient care.

IronXL Licensing

IronXL is an enterprise library part of Iron Suite of products from Iron Software. It requires a license to run. Users can download a trial license to work with using their email ID from here. Once the data is entered, the license is delivered to the email ID provided. This license needs to be placed at the beginning of the code, before using the IronXL library as below.

License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
$vbLabelText   $csharpLabel

Conclusion

IronXL is a powerful .NET library for creating, reading, and editing Excel files, offering an intuitive API that simplifies the process of working with Excel documents. It supports a wide range of Excel formats, including XLS, XLSX, and CSV, making it versatile for various use cases. IronXL allows easy manipulation of cell values, formulas, and formatting, and is optimized for performance, efficiently handling large files and complex operations. Its efficient memory management ensures responsive applications, and its cross-platform compatibility makes it a valuable tool for developers working on different operating systems.

常见问题解答

如何在没有安装 Microsoft Excel 的情况下在 C# 中操作 Excel 文件?

您可以使用 IronXL,这是一款来自 Iron Software 的 C# 库,用于读取、写入和操作 Excel 文档,而无需 Microsoft Excel。它支持多种格式,如 XLS、XLSX 和 CSV,并可用于如 Web 服务、桌面和控制台等应用。

在 C# 中设置一个 Visual Studio 项目以处理 Excel 涉及哪些步骤?

要在 C# 中设置一个处理 Excel 的 Visual Studio 项目,请通过 NuGet 包管理器安装 IronXL。在包管理器控制台中使用命令:dotnet add package IronXL.Excel --version 2024.8.5 将该库添加到您的项目。

我可以使用 C# 在 Excel 文件中进行计算吗?

是的,使用 IronXL,您可以在 Excel 文件中进行计算。该库支持 Excel 公式,允许您直接在 C# 应用程序中自动化计算。

我如何使用 C# 将 Excel 文件转换为 HTML?

IronXL 提供了 ExportToHtml 方法来将 Excel 文件转换为 HTML。此方法允许自定义选项以确保 HTML 输出符合您的要求。

在 C# 中使用 IronXL 操作 Excel 文件的好处是什么?

IronXL 提供易于使用的直观 API、针对大型 Excel 文件优化的性能以及各种应用的多功能性。其跨平台兼容性和全面的文档使其效用更上一层楼。

我可以使用 IronXL 将高级样式应用于 Excel 单元格吗?

可以,使用 IronXL,您可以将高级样式应用于 Excel 单元格,比如通过每个单元格的样式属性自定义字体、大小、颜色、边框和对齐方式。

IronXL 是否适合跨平台 Excel 文件操作?

是的,IronXL 被设计为跨平台的,兼容 Windows、macOS、Linux 以及 Docker、Azure 和 AWS 等环境,使其成为多种部署方案的理想选择。

我如何在 C# 中使用 IronXL 读取 Excel 文件中的单元格值?

使用 IronXL,您可以通过加载文件使用 WorkBook.Load,选择工作表,并根据地址访问特定的单元格值或范围来读取 Excel 文件中的单元格值。

是什么使 IronXL 成为处理 C# 中 Excel 文件的强大工具?

IronXL 因其对多种格式(XLS、XLSX、CSV)的支持、公式和样式能力、安全的加密以及在各种操作系统上高效处理大文件的能力而强大。

Curtis Chau
技术作家

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

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