跳至页脚内容
使用 IRONXL
如何将数据表转换为Excel文件

C# 中 DataTable 到 Excel(代码示例教程)

It can be tough to programmatically alter an Excel spreadsheet, for two main reasons. First, when dealing with spreadsheets, users must maintain a consistent interface and document structure, which is not always straightforward. Second, it's not always clear which code will work in specific situations, particularly when sophisticated computations are involved. There are numerous reasons why programmatically creating an Excel file is difficult. Programmers must first transform the data in the Excel document into a readable format, then parse the data and parse it back, which is even more difficult. I've come up with a solution to this issue. I'll teach you how to make an Excel file and programmatically export a DataTable to an Excel sheet without any problem using the IronXL .NET Excel library. Let's get started:

IronXL Features

  • IronXL runs on a variety of Operating Systems, including Windows, Linux, and macOS.
  • Almost all of the .NET Frameworks are supported by IronXL, including the Console, Windows Forms Application, and Web Application.
  • IronXL makes reading Excel files straightforward and easy.
  • We can load, edit, export Datatables, export datasets, and read Excel file formats such as XLSX files, XLS, CSV, TSV, XLST, XLSM files, and more with IronXL.
  • IronXL allows us to save and export files with a variety of extensions, including XLS, CSV, TSV, JSON, XLSX, and others.
  • Excel formulas can be created by IronXL.
  • Text, Numbers, Formulas, Dates, Currency, Percentages, and other Excel cell data formats are supported by IronXL.
  • It also provides numerous sorting options such as Range, Columns, and Rows, among others.
  • Cell styling in IronXL includes font, size, background pattern, border, and alignment, among others.
  • We can read and export data from an Excel file using IronXL.
  • IronXL does not require Excel or Interop to be installed on your server. The IronXL API is faster and easier to use than Microsoft Office, Interop, and Excel.

1 Creating a New Project in Visual Studio

To use the IronXL library, we must create a .NET project in Visual Studio. You can use any version of Visual Studio, but the latest version is recommended. You can create an application like Windows Forms or different project templates, depending on your requirements. I will use the Console Application for this tutorial, for simplicity.

How to Export Huge Data From Datatable to Excel in C#, Figure 1: Create a new project UI in Visual Studio Create a new project UI in Visual Studio

Next, enter the project name and the location of the project.

How to Export Huge Data From Datatable to Excel in C#, Figure 2: Configuration step in creating a new project Configuration step in creating a new project

Next, select the framework below. In this project, we are going to use .NET Core 6.

How to Export Huge Data From Datatable to Excel in C#, Figure 3: .Net Framework selection UI .Net Framework selection UI

Once the Application creates the solution, it will open the program.cs file where you can enter the code and build/run the application.

How to Export Huge Data From Datatable to Excel in C#, Figure 4: Empty program.cs file on the new project Empty program.cs file on the new project

Next, we can add the library to test the code.

2 Install the IronXL Library

The IronXL Library can be downloaded and installed in four ways.

These are:

  • Using Visual Studio
  • Using the Visual Studio Command Line.
  • Direct download from the NuGet website.
  • Direct download from the IronXL website.

2.1 Using Visual Studio

We can install the IronXL library using NuGet Package Manager. You must first open the NuGet Package manager and then search for IronXL in the browse tab. Select IronXL from the search results and install it. After that, our project will be ready to use in the IronXL library.

The below screenshot shows how we can open the NuGet Package Manager in Visual Studio.

How to Export Huge Data From Datatable to Excel in C#, Figure 5: Navigate to NuGet Package Manager in Visual Studio Navigate to NuGet Package Manager in Visual Studio

IronXL in search results:

How to Export Huge Data From Datatable to Excel in C#, Figure 6: Search for IronXL library Search for IronXL library

2.2 Using the Visual Studio Command-Line

Many people love to use a Console to perform operations. So, we can install it by Console too. Follow the steps below to install IronXL via the command line.

  • In Visual Studio, go to Tools-> NuGet Package Manager -> Package Manager Console.
  • Enter the following line in the Package Manager Console tab:
Install-Package IronXL.Excel

Now the package will download/install to the current project and be ready to use.

How to Export Huge Data From Datatable to Excel in C#, Figure 7: Install IronXL package via Console Install IronXL package via Console

2.3 Direct download from the NuGet website

The third way is to download the NuGet package directly from the website.

  • Navigate to the NuGet official IronXL package page.
  • Select the download package option from the menu on the right-hand side.
  • Double-click the downloaded package. It will be installed automatically.
  • Next, reload the solution and start using it in the project.

2.4 Direct download from the IronXL website

Click the link to download the latest package directly from the website. Once downloaded, follow the steps below to add the package to the project.

  • Right-click the project from the solution window.
  • Then, select the options reference and browse the location of the downloaded reference.
  • Next, click ok to add the reference.

3 Export Datatable to Excel File using IronXL

IronXL allows us to export DataTables to Excel files easily with a limited number of steps.

First, we need to include the namespace of IronXL as in the code screenshot below. Once it is added, we can use the IronXL classes and methods in our code.

How to Export Huge Data From Datatable to Excel in C#, Figure 8: Include namespace of IronXL before using the library Include namespace of IronXL before using the library

IronXL allows us to create Excel files and convert them into workbook objects. After converting them into objects, we can perform various types of operations. In the sample code below, we will convert a DataTable into an Excel worksheet, and then we can create an Excel file.

using System;
using System.Data;
using IronXL;

public class ExcelExporter
{
    /// <summary>
    /// Exports a DataTable to an Excel file using IronXL.
    /// </summary>
    /// <param name="filePath">The file path where the Excel file will be saved.</param>
    public static void ExportToExcel(string filePath)
    {
        // Creating a DataTable with a single column
        DataTable table = new DataTable();
        table.Columns.Add("DataSet_Animal", typeof(string));

        // Adding some rows to the DataTable
        table.Rows.Add("Lion");
        table.Rows.Add("Tiger");
        table.Rows.Add("Cat");
        table.Rows.Add("Goat");
        table.Rows.Add("Panther");
        table.Rows.Add("Fox");
        table.Rows.Add("Cheetah");

        // Creating a new Excel Workbook
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Accessing the default worksheet
        WorkSheet ws = wb.DefaultWorkSheet;

        // Iterating through the DataTable rows
        int rowCount = 1;
        foreach (DataRow row in table.Rows)
        {
            // Adding each DataRow's first column value to the corresponding cell in the worksheet
            ws["A" + rowCount].Value = row[0].ToString();
            rowCount++;
        }

        // Saving the workbook to a CSV file at specified file path with ";" as delimiter
        wb.SaveAsCsv(filePath, ";");
    }
}
using System;
using System.Data;
using IronXL;

public class ExcelExporter
{
    /// <summary>
    /// Exports a DataTable to an Excel file using IronXL.
    /// </summary>
    /// <param name="filePath">The file path where the Excel file will be saved.</param>
    public static void ExportToExcel(string filePath)
    {
        // Creating a DataTable with a single column
        DataTable table = new DataTable();
        table.Columns.Add("DataSet_Animal", typeof(string));

        // Adding some rows to the DataTable
        table.Rows.Add("Lion");
        table.Rows.Add("Tiger");
        table.Rows.Add("Cat");
        table.Rows.Add("Goat");
        table.Rows.Add("Panther");
        table.Rows.Add("Fox");
        table.Rows.Add("Cheetah");

        // Creating a new Excel Workbook
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Accessing the default worksheet
        WorkSheet ws = wb.DefaultWorkSheet;

        // Iterating through the DataTable rows
        int rowCount = 1;
        foreach (DataRow row in table.Rows)
        {
            // Adding each DataRow's first column value to the corresponding cell in the worksheet
            ws["A" + rowCount].Value = row[0].ToString();
            rowCount++;
        }

        // Saving the workbook to a CSV file at specified file path with ";" as delimiter
        wb.SaveAsCsv(filePath, ";");
    }
}
Imports System
Imports System.Data
Imports IronXL

Public Class ExcelExporter
	''' <summary>
	''' Exports a DataTable to an Excel file using IronXL.
	''' </summary>
	''' <param name="filePath">The file path where the Excel file will be saved.</param>
	Public Shared Sub ExportToExcel(ByVal filePath As String)
		' Creating a DataTable with a single column
		Dim table As New DataTable()
		table.Columns.Add("DataSet_Animal", GetType(String))

		' Adding some rows to the DataTable
		table.Rows.Add("Lion")
		table.Rows.Add("Tiger")
		table.Rows.Add("Cat")
		table.Rows.Add("Goat")
		table.Rows.Add("Panther")
		table.Rows.Add("Fox")
		table.Rows.Add("Cheetah")

		' Creating a new Excel Workbook
		Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)

		' Accessing the default worksheet
		Dim ws As WorkSheet = wb.DefaultWorkSheet

		' Iterating through the DataTable rows
		Dim rowCount As Integer = 1
		For Each row As DataRow In table.Rows
			' Adding each DataRow's first column value to the corresponding cell in the worksheet
			ws("A" & rowCount).Value = row(0).ToString()
			rowCount += 1
		Next row

		' Saving the workbook to a CSV file at specified file path with ";" as delimiter
		wb.SaveAsCsv(filePath, ";")
	End Sub
End Class
$vbLabelText   $csharpLabel

In the above code, we are exporting the DataTable to an Excel file. First, we are creating a DataTable, and then we are creating column headers. After creating the columns, we add the rows one by one. Once the rows are added, we create the WorkBook object. By using the object, we can add the data to the Excel sheet, and then we can save the data to the location. We are creating the WorkSheet object which allows for creating a worksheet, and then we can add this to the WorkBook object.

We are using a foreach loop to read the DataTable values one by one and then we add the value to the worksheet. Once all the values are added to the worksheet, we then save them into a CSV file using the method called SaveAsCsv — we need to pass the delimiter and file name with location as a parameter. A delimiter is an optional parameter that we can ignore if it is not required.

How to Export Huge Data From Datatable to Excel in C#, Figure 9: The completed code in Visual Studio The completed code in Visual Studio

The above is the full screenshot of the code which we are using on the .NET Core 6.

Result:

How to Export Huge Data From Datatable to Excel in C#, Figure 10: The result when opening the file in Microsoft Excel The result when opening the file in Microsoft Excel

Above is the result of the executed code sample. In the screenshot, all the data available in the DataTable has been added to the newly created Excel sheet one by one.

4 Conclusion

IronXL is one of the most commonly used Excel libraries. It does not depend on any other third-party library. It is independent and does not need MS Excel to be installed. It works on multiple platforms. The introductory price for IronXL starts at $799. Also, it provides the option of a one-year fee for product support and updates. IronXL provides royalty-free redistribution coverage at an extra cost. To know more about the price details, visit our licensing page.

常见问题解答

如何在 C# 中将 DataTable 导出到 Excel 文件?

您可以使用 IronXL 的 WorkBook 和 WorkSheet 类将 DataTable 导出到 Excel 文件。创建一个 DataTable,遍历其行,并使用 IronXL 的 API 用数据填充 Excel 文件。

使用 IronXL 进行 Excel 操作相比 Interop 有哪些好处?

IronXL 比 Microsoft Interop 更快且更高效,不需要安装 Microsoft Excel,并支持多种平台和文件格式。

IronXL支持哪些Excel文件格式?

IronXL 支持各种 Excel 文件格式,包括 XLSX、XLS、CSV、TSV、XLST 和 XLSM,允许多种文件操作。

IronXL 可以在导出数据时处理 Excel 公式吗?

是的,IronXL 可以处理 Excel 公式,确保从 DataTable 导出到 Excel 文件时复杂的计算被保留。

哪些操作系统与 IronXL 兼容?

IronXL 兼容多种操作系统,包括 Windows、Linux 和 macOS,允许跨平台开发。

是否必须安装Microsoft Excel才能使用IronXL?

不需要,IronXL 独立于 Microsoft Excel 运作,允许您处理 Excel 文件而无需在服务器上安装 Excel。

如何在 C# 项目中安装 IronXL?

您可以通过 Visual Studio 中的 NuGet 包管理器、使用命令行或直接从 NuGet 或 IronXL 网站下载来安装 IronXL。

IronXL 支持哪些 .NET 框架?

IronXL 支持多种 .NET 框架,包括控制台应用程序、Windows 窗体应用程序和 Web 应用程序,使其适用于不同类型的项目。

IronXL 是否支持 Excel 文件中的单元格样式和格式?

是的,IronXL 提供多种单元格样式和格式选项,例如设置字体样式、颜色和边框,以增强 Excel 文件的外观。

IronXL 如何简化编程创建 Excel 文件的过程?

IronXL 通过提供易用的 API 来创建、修改和导出 Excel 文件,简化了这一过程,而无需维护其他方法所需的接口和结构。

Curtis Chau
技术作家

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

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