使用IRONXL

如何在C#中将DataGridView导出到Excel

发布 2024年一月27日
分享:

本教程全面介绍了如何从 数据网格视图控件 在 Windows 窗体应用程序中使用 铁XL 库。我们的重点是为希望将 Microsoft Excel 功能集成到其 C# 项目中的初学者创建无缝体验。

如何在 C&num 中将 DataGridView 导出到 Excel;

1.在 Visual Studio 中创建一个 C# Windows Forms 项目。

2.使用 NuGet 包管理器安装 Excel 库。

3.在 Windows 窗体用户界面中创建一个 DataGridView 和一个按钮。

4.为 DataGridView 附加数据源。

5.在按钮的单击事件处理程序中应用数据导出逻辑。

IronXL 入门

铁XL 是一个强大的库,可简化在.NET Framework 应用程序中处理 Excel 文档的过程。它允许您导出大型 Excel 文件、处理复杂的数据源,并为 .NET Excel 文件操作提供广泛支持,而无需 Microsoft Excel 对象库。让我们来建立我们的项目。

设置项目

1.创建新的 Windows 窗体应用程序

打开 Visual Studio 并创建一个新的 Windows 窗体应用程序。这将是我们项目的基础,我们将在这里实现将 DataGridView 数据导出到 Excel 文件的功能。

如何用 C# 将 DataGridView 导出到 Excel:图 1 - 在 Visual Studio 中创建新的 Windows 窗体应用程序

2.安装 IronXL

IronXL 可以轻松添加到项目中。在 Visual Studio 中,导航至 "Manage NuGet Packages(管理 NuGet 软件包)"选项,搜索 IronXL 并安装。此操作将处理在 C# 中将 DataGridView 导出到 Excel 所需的所有依赖项。

如何用 C# 将 DataGridView 导出到 Excel:图 2 - 通过 NuGet 包管理器安装 IronXL 库

3.准备用户界面

在表单中添加 DataGridView 控件。该控件将保存我们打算导出的数据。此外,添加一个按钮来触发导出过程。您可以将其标记为 "导出到 Excel "或类似内容。

实现导出功能

在本节中,我们将具体介绍如何编程,以便使用 IronXL 将数据从 Windows 窗体应用程序中的 DataGridView 导出到 Excel 文档。

构建应用程序

首先,您需要在表单中添加 DataGridView 控件。该控件是导出数据前显示数据的主要组件。您可以从 Visual Studio 的工具箱中将 DataGridView 拖到窗体上,从而轻松添加该控件。我们还可以添加一个按钮,将 DataGridView 数据导出到 Excel 文件。

如何用 C# 将 DataGridView 导出到 Excel:图 3 - 添加将 DataGridView 数据导出到 Excel 文件的按钮

下一步是将数据加载到 DataGridView 中。这些数据有多种来源,如数据表数据集。如果您刚开始使用,可能需要以编程方式创建一个新的 DataSetDataTable 并填充示例数据,以了解它是如何工作的。或者,你也可以从外部导入数据。这里的关键是将数据源绑定到 DataGridView,从而有效地将数据链接到网格。一旦将数据绑定到 DataGridView,就可以在表单的网格中看到这些数据。

private void BindDataToDataGridView()
{
    // Create a new DataTable.
    DataTable dataTable = new DataTable();
    // Define columns for the DataTable.
    dataTable.Columns.Add("Employee ID", typeof(int));
    dataTable.Columns.Add("Name", typeof(string));
    dataTable.Columns.Add("Department", typeof(string));
    dataTable.Columns.Add("Joining Date", typeof(DateTime));
    // Add sample data to the DataTable.
    for (int i = 1; i <= 25; i++)
    {
        dataTable.Rows.Add(i, "Employee " + i, "Department " + (i % 5 + 1), DateTime.Now.AddDays(-i * 15));
    }
    // Bind the DataTable to the DataGridView.
    dataGridView1.DataSource = dataTable;
}
private void BindDataToDataGridView()
{
    // Create a new DataTable.
    DataTable dataTable = new DataTable();
    // Define columns for the DataTable.
    dataTable.Columns.Add("Employee ID", typeof(int));
    dataTable.Columns.Add("Name", typeof(string));
    dataTable.Columns.Add("Department", typeof(string));
    dataTable.Columns.Add("Joining Date", typeof(DateTime));
    // Add sample data to the DataTable.
    for (int i = 1; i <= 25; i++)
    {
        dataTable.Rows.Add(i, "Employee " + i, "Department " + (i % 5 + 1), DateTime.Now.AddDays(-i * 15));
    }
    // Bind the DataTable to the DataGridView.
    dataGridView1.DataSource = dataTable;
}
Private Sub BindDataToDataGridView()
	' Create a new DataTable.
	Dim dataTable As New DataTable()
	' Define columns for the DataTable.
	dataTable.Columns.Add("Employee ID", GetType(Integer))
	dataTable.Columns.Add("Name", GetType(String))
	dataTable.Columns.Add("Department", GetType(String))
	dataTable.Columns.Add("Joining Date", GetType(DateTime))
	' Add sample data to the DataTable.
	For i As Integer = 1 To 25
		dataTable.Rows.Add(i, "Employee " & i, "Department " & (i Mod 5 + 1), DateTime.Now.AddDays(-i * 15))
	Next i
	' Bind the DataTable to the DataGridView.
	dataGridView1.DataSource = dataTable
End Sub
VB   C#

处理按钮点击事件

我们与用户的主要交互点是 Windows 窗体中的一个按钮。点击该按钮后,将启动导出过程。下面是如何设置这种交互的方法:

  • 在 Windows 窗体中,应该有一个专门用于导出 DataGridView 数据的按钮。
  • 该按钮在 C# 代码中有一个事件处理程序方法。当用户单击该按钮时,将触发该方法。
private void btnExport_Click(object sender, EventArgs e)
{
    // Code to export data will go here
}
private void btnExport_Click(object sender, EventArgs e)
{
    // Code to export data will go here
}
Private Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Code to export data will go here
End Sub
VB   C#

从 DataGridView 导出数据

要导出 DataGridView 数据,我们首先需要引用 IronXL 命名空间:

using IronXL;
using IronXL;
Imports IronXL
VB   C#

在事件处理程序中,第一步是使用 IronXL 初始化一个新的工作簿和工作表。我们将在这里传输来自 DataGridView 的数据。

  • 一个 WorkBook 对象代表整个 Excel 文件。
  • 工作簿中的 WorkSheet 就像 Excel 文件中的单个页面或选项卡。

在这里,我们创建一个工作簿,然后添加一个工作表。工作表的名称是 "ExportedData",但你可以选择任何适合你的应用程序的名称。

WorkBook workbook = new WorkBook();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
WorkBook workbook = new WorkBook();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
Dim workbook As New WorkBook()
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("ExportedData")
VB   C#

填充 Excel 表

下一步是遍历 DataGridView 的行和列,并将每个单元格的数据复制到 Excel 工作表的相应单元格中。

  • 外部循环遍历每一行,内部循环遍历相应行中的每一列。
  • 我们将 DataGridView 中每个单元格的值分配给 Excel 工作表中的相应单元格。这可以使用索引 i (行数) 和j (专栏).
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        // Convert row and column index to Excel cell address format
        string cellAddress = ConvertToCellAddress(i, j);
        worksheet [cellAddress].Value = dataGridView1.Rows [i].Cells [j].Value.ToString();
    }
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    for (int j = 0; j < dataGridView1.Columns.Count; j++)
    {
        // Convert row and column index to Excel cell address format
        string cellAddress = ConvertToCellAddress(i, j);
        worksheet [cellAddress].Value = dataGridView1.Rows [i].Cells [j].Value.ToString();
    }
}
For i As Integer = 0 To dataGridView1.Rows.Count - 1
	For j As Integer = 0 To dataGridView1.Columns.Count - 1
		' Convert row and column index to Excel cell address format
		Dim cellAddress As String = ConvertToCellAddress(i, j)
		worksheet (cellAddress).Value = dataGridView1.Rows (i).Cells (j).Value.ToString()
	Next j
Next i
VB   C#

要将行和列索引转换为 Excel 单元格地址,可以使用类似这样的辅助方法:

private string ConvertToCellAddress(int row, int column)
{
    // Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
    // The following code converts a column index to this format.
    string columnLabel = "";
    while (column >= 0)
    {
        columnLabel = (char)('A' + column % 26) + columnLabel;
        column = column / 26 - 1;
    }
    // Rows in Excel are labeled as 1, 2, 3, ..., n
    // Adding 1 because Excel is 1-based and our loop is 0-based.
    string rowLabel = (row + 1).ToString();
    return columnLabel + rowLabel;
}
private string ConvertToCellAddress(int row, int column)
{
    // Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
    // The following code converts a column index to this format.
    string columnLabel = "";
    while (column >= 0)
    {
        columnLabel = (char)('A' + column % 26) + columnLabel;
        column = column / 26 - 1;
    }
    // Rows in Excel are labeled as 1, 2, 3, ..., n
    // Adding 1 because Excel is 1-based and our loop is 0-based.
    string rowLabel = (row + 1).ToString();
    return columnLabel + rowLabel;
}
Private Function ConvertToCellAddress(ByVal row As Integer, ByVal column As Integer) As String
	' Columns in Excel are labeled as A, B, C, ..., Z, AA, AB, ..., etc.
	' The following code converts a column index to this format.
	Dim columnLabel As String = ""
	Do While column >= 0
		columnLabel = ChrW(AscW("A"c) + column Mod 26) & columnLabel
		column = column \ 26 - 1
	Loop
	' Rows in Excel are labeled as 1, 2, 3, ..., n
	' Adding 1 because Excel is 1-based and our loop is 0-based.
	Dim rowLabel As String = (row + 1).ToString()
	Return columnLabel & rowLabel
End Function
VB   C#

保存 Excel 文件

传输完所有数据后,下一步就是将工作簿保存为 Excel 文件。此步骤将在系统中创建一个 Excel 文件,并指定路径。

workbook.SaveAs("DataGridViewExport.xlsx");
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
workbook.SaveAs("DataGridViewExport.xlsx");
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
workbook.SaveAs("DataGridViewExport.xlsx")
MessageBox.Show("Data exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
VB   C#

错误处理

在任何数据导出过程中,处理异常对于确保应用程序的稳定性都至关重要。将导出逻辑封装在 try-catch 块中可确保在导出过程中出现的任何问题都能得到及时处理。 (如文件访问权限、数据格式问题等。) 并从容应对。

try
{
    // Export logic
}
catch (Exception ex)
{
    MessageBox.Show("An exception occurred: " + ex.Message);
}
try
{
    // Export logic
}
catch (Exception ex)
{
    MessageBox.Show("An exception occurred: " + ex.Message);
}
Try
	' Export logic
Catch ex As Exception
	MessageBox.Show("An exception occurred: " & ex.Message)
End Try
VB   C#

输出

运行程序后,就会出现这个界面:

如何用 C# 将 DataGridView 导出到 Excel:图 4 - 先前代码的输出形式

在这里,你可以看到数据已显示在 DataGridView 中。现在,点击导出按钮。它将把数据从 DataGridView 导出到 Excel 文件。

如何用 C# 将 DataGridView 导出到 Excel:图 5 - 成功导出信息

在此,您可以看到出现了一个消息框,数据被导出到 Excel 文件中。下面是输出的 Excel 文件:

如何用 C# 将 DataGridView 导出到 Excel:图 6 - 导出上一个表格后输出的 Excel 文件

结论

通过本指南,您现在有了一个基本但功能强大的工具,可以使用 C# 和 铁XL.这一功能对于需要进行数据分析、报告或在不同格式之间传输数据的应用程序来说至关重要。请记住,尝试使用 DataGridView 控件和 IronXL 库的不同功能可以实现更多自定义和高级功能。

IronXL 提供了 免费试用 您可以用它来探索其功能。许可证起价为 $749,对于在 .NET 应用程序中寻求可靠、高效的 Excel 文件操作解决方案的专业人士和组织机构来说,这是一项值得投资的项目。

您的旅程不会就此结束。请继续探索 IronXL 的更多功能以及增强 Windows 窗体应用程序的其他方法。编码快乐!

< 前一页
如何在C#控制台应用程序中读取Excel文件
下一步 >
如何读取CSV文件中的数据并将其存储在数据库中 C#

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 988,189 查看许可证 >