跳至页脚内容
使用 IRONXL
如何将 DataGridView 导出到 Excel 中的 C#

如何将Datagridview导出到C#中的Excel

本教程提供了一份全面的指南,介绍如何使用C#中的IronXL库将Windows Forms应用程序中的DataGridView 控件中的数据导出到Excel文件。 我们的重点是为希望将Microsoft Excel功能集成到其C#项目中的初学者创造无缝体验。

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

  1. 在Visual Studio中创建一个C# Windows Forms项目。
  2. 使用NuGet包管理器安装Excel库。
  3. 在Windows Form UI中创建一个DataGridView和一个按钮。
  4. 将数据源附加到DataGridView。
  5. 在按钮的点击事件处理程序中应用数据导出逻辑。

IronXL入门指南

IronXL是一个强大的库,它简化了在.NET Framework应用程序中处理Excel文档的过程。 它允许您导出大型Excel文件,处理复杂数据源,并在不需要Microsoft Excel对象库的情况下提供对.NET Excel文件操作的广泛支持。 让我们设置我们的项目。

设置您的项目

1. 创建一个新的Windows Forms应用程序

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

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

2. 安装IronXL

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

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

3. 准备用户界面

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

实现导出功能

在本节中,我们将教您如何编写功能,允许在Windows Forms应用程序中使用IronXL从DataGridView导出数据到Excel文档。

构建应用程序

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

如何在C#中将DataGridView导出到Excel:图3 - 添加一个按钮以将DataGridView数据导出到Excel文件

接下来的步骤是将数据加载到DataGridView中。 此数据可以来自各种来源,例如DataTableDataSet。 如果您是刚开始,您可能希望以编程方式创建一个新的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
$vbLabelText   $csharpLabel

处理按钮点击事件

我们与用户的主要交互点将是在我们的Windows Form内的一个按钮。 当点击时,此按钮启动导出过程。 以下是您如何设置这种互动:

  • 在您的Windows Form中,您应该有一个专用于导出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
$vbLabelText   $csharpLabel

从DataGridView导出数据

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

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

在事件处理程序内,第一步是使用IronXL初始化新的工作簿和工作表。 这是我们将从DataGridView传输数据的地方。

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

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

WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");
Dim workbook As WorkBook = WorkBook.Create()
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("ExportedData")
$vbLabelText   $csharpLabel

填充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
$vbLabelText   $csharpLabel

要将行和列索引转换为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
$vbLabelText   $csharpLabel

保存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)
$vbLabelText   $csharpLabel

错误处理

在任何数据导出过程中,处理异常是确保应用程序稳定性的关键。 将导出逻辑包装在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
$vbLabelText   $csharpLabel

输出

运行程序后,将显示此界面:

如何在C#中将DataGridView导出到Excel:图4 - 上述代码的输出表单

在这里,您可以看到数据在DataGridView中显示。 现在,点击导出按钮。 它会将DataGridView中的数据导出到Excel文件。

如何在C#中将DataGridView导出到Excel:图5 - 成功导出消息

在这里,您可以看到一个消息框出现,数据已导出到Excel文件。以下是输出的Excel文件:

如何在C#中将DataGridView导出到Excel:图6 - 导出上述表单后的输出Excel文件

结论

通过遵循本指南,您现在有一个基本但强大工具,可以使用C#和IronXL将DataGridView数据导出到Excel文件中。 此功能对于需要数据分析、报告或仅仅在不同格式之间传输数据的应用程序至关重要。 请记住,在DataGridView控件和IronXL库中尝试不同的功能,可以导致更多定制化和高级实现。

IronXL提供免费试用,您可以使用它来探索其功能。 许可证从$liteLicense起步,这对于寻求.NET应用程序中Excel文件操作可靠且高效解决方案的专业人士和组织来说是值得的投资。

您的旅程并未结束。 继续探索IronXL的更多功能及其他增强Windows Forms应用程序的方法。 祝您编码愉快!

常见问题解答

如何在 C# 中将 DataGridView 数据导出到 Excel 文件?

您可以使用 IronXL 库在 C# 中将 DataGridView 数据导出到 Excel 文件。这涉及创建一个 Windows Forms 项目,通过 NuGet 安装 IronXL,并实现将数据从 DataGridView 转移到 Excel 工作表的逻辑。

设置 DataGridView 以导出到 Excel 涉及哪些步骤?

步骤包括在 Windows Forms 项目中创建一个 DataGridView,将其绑定到数据源,向表单中添加一个按钮,并使用 IronXL 库在按钮的点击事件处理程序中编写导出逻辑。

如何在 Visual Studio 项目中安装 IronXL?

要在 Visual Studio 项目中安装 IronXL,导航到“管理 NuGet 包”,搜索 IronXL,并安装它以处理导出 DataGridView 到 Excel 所需的所有必要依赖项。

我可以使用 IronXL 导出大型 Excel 文件吗?

是的,IronXL 允许导出大型 Excel 文件,提供强大的功能来处理大量数据集,而无需使用 Microsoft Excel 对象库。

按钮在 DataGridView 导出教程中的作用是什么?

教程中的按钮触发导出过程。点击后,它会执行逻辑以使用 IronXL 库将数据从 DataGridView 转移到 Excel 文件。

IronXL 如何处理 DataGridView 到 Excel 的数据传输?

IronXL 通过遍历 DataGridView 的行和列,并将每个单元格的数据复制到相应的 Excel 工作表单元格中来促进数据传输。

如何使用 IronXL 在导出过程中管理错误?

您可以通过将您的导出逻辑包装在 try-catch 代码块中来捕获和处理异常,从而即使在遇到如文件访问权限等问题时也能确保流畅运行。

如何在从 DataGridView 导出数据后保存 Excel 文件?

一旦使用 IronXL 将数据传输到 Excel 工作表中,您可以使用 IronXL 的 SaveAs 方法将文件保存到您的系统。

IronXL 是否可提供免费试用以测试其功能?

是的,IronXL 提供免费试用,允许用户探索其在 .NET 应用程序中的 Excel 文件操作功能。进一步开发需要许可。

Curtis Chau
技术作家

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

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