
如何将Datagridview导出到C#中的Excel
本教程提供了关于如何在Windows Forms应用程序中使用IronXL库通过C#从DataGridView 控件导出数据到Excel文件的综合指南。 我们的重点是为希望将Microsoft Excel功能集成到其C#项目中的初学者创造无缝体验。
How to Export DataGridView to Excel in C#
- 在Visual Studio中创建一个C# Windows Forms项目。
- 使用NuGet包管理器安装Excel库。
- 在Windows Form UI中创建一个DataGridView和一个按钮。
- 将数据源附加到DataGridView。
- 在按钮的点击事件处理程序中应用数据导出逻辑。
IronXL入门指南
IronXL是一个强大的库,它简化了在.NET Framework应用程序中处理Excel文档的过程。 它允许您导出大型Excel文件,处理复杂数据源,并在不需要Microsoft Excel对象库的情况下提供对.NET Excel文件操作的广泛支持。 让我们设置我们的项目。
设置您的项目
1. 创建一个新的Windows Forms应用程序
打开Visual Studio并创建一个新的Windows Forms应用程序。 这将成为我们的项目基础,我们将在其中实现在将DataGridView数据导出到Excel文件的功能。

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

3. 准备用户界面
将一个DataGridView控件添加到您的表单中。 此控件将保存我们打算导出的数据。 另外,添加一个按钮以触发导出过程。 您可以将其标记为"导出到Excel"或类似的标签。
实现导出功能
在本节中,我们将教您如何编写功能,允许在Windows Forms应用程序中使用IronXL从DataGridView导出数据到Excel文档。
构建应用程序
首先,您需要向您的表单添加一个DataGridView控件。 此控件是主要组件,您的数据将在导出前显示。 您可以通过从Visual Studio的工具箱中拖动一个DataGridView到您的表单中轻松添加它。 我们还可以添加一个按钮来将DataGridView数据导出到Excel文件。

接下来的步骤是将数据加载到DataGridView中。 这些数据可以来自各种来源,比如DataSet。 如果您是初学者,您可能希望以编程方式创建新的DataTable,并使用示例数据填充它,以查看其运行效果。 或者,您可以从外部来源导入数据。 关键是将您的数据源绑定到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 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处理按钮点击事件
我们与用户的主要交互点将是在我们的Windows Form内的一个按钮。 当点击时,此按钮启动导出过程。 以下是您如何设置这种互动:
- 在您的Windows Form中,您应该有一个专用于导出DataGridView数据的按钮。
- 此按钮在您的C#代码中有一个事件处理方法。 当用户点击按钮时,将触发此方法。
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从DataGridView导出数据
要导出DataGridView数据,我们首先需要引用IronXL命名空间:
using IronXL;Imports IronXL在事件处理程序内,第一步是使用IronXL初始化新的工作簿和工作表。 这是我们将从DataGridView传输数据的地方。
- 一个
WorkBook对象代表整个Excel文件。 - 工作簿中的
WorkSheet类似于Excel文件中的单个页面或标签。
在这里,我们创建一个工作簿然后向其添加一个工作表。 工作表名为"ExportedData",但您可以选择任何适合您应用程序上下文的名称。
WorkBook workbook = WorkBook.Create();
WorkSheet worksheet = workbook.CreateWorkSheet("ExportedData");Dim workbook As WorkBook = WorkBook.Create()
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("ExportedData")填充Excel表
下一步涉及遍历DataGridView的行和列,并将每个单元格的数据复制到Excel工作表中对应的单元格。
- 外循环遍历每一行,而内循环遍历相应行中的每一列。
- 我们将DataGridView中每个单元格的值分配给Excel工作表中的相应单元格。 这是通过使用索引
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 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要将行和列索引转换为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 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保存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)错误处理
在任何数据导出过程中,处理异常是确保应用程序稳定性的关键。 将导出逻辑包装在try-catch块中,确保在导出过程中遇到的任何问题(如文件访问权限、数据格式问题等)都被捕获和妥善处理。
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输出
运行程序后,将显示此界面:

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

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

结论
通过遵循本指南,您现在有一个基本但强大工具,可以使用C#和IronXL将DataGridView数据导出到Excel文件中。 此功能对于需要数据分析、报告或仅仅在不同格式之间传输数据的应用程序至关重要。 请记住,在DataGridView控件和IronXL库中尝试不同的功能,可以导致更多定制化和高级实现。
IronXL提供免费试用,您可以使用它来探索其功能。 许可证从$999起步,这对于寻求.NET应用程序中Excel文件操作可靠且高效解决方案的专业人士和组织来说是值得的投资。
您的旅程并未结束。 继续探索IronXL的更多功能及其他增强Windows Forms应用程序的方法。 祝您编码愉快!

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



