跳至页脚内容
使用 IRONXL

C# DataGridView Export to Excel with Formatting:完整指南

C# DataGridView Export to Excel with Formatting:完整指南:图片 1 - C# DataGridView 通过格式化导出到 Excel

在 Windows 窗体应用程序中,将 DataGridView 数据导出到 Excel 文件是一项常见要求。 无论是生成报告还是传输用于分析的数据,开发人员都需要一种可靠的方法来导出 DataGridView 内容,同时保留格式。 在本文中,我们将向您展示如何使用 IronXL 将 DataGridView 导出到 Excel,这是一种无需安装 Microsoft Excel 即可完美运行的现代方法。

立即开始使用 IronXL。
green arrow pointer

如何为数据网格视图导出设置 Windows 窗体项目?

传统方法需要通过 COM 选项卡向 Microsoft Excel 对象库添加引用。 然而,这种方法有很大的缺点:它需要在每台机器上安装 Microsoft Excel,涉及使用 private void releaseobject 方法释放对象的复杂模式,并且在处理大型 Excel 文件时效果不佳。

IronXL 完全解决了这些问题。 在 Visual Studio 中,只需通过 NuGet 包管理器进行安装即可,无需选择添加引用菜单或导航到 COM 选项卡。 该库可处理所有数据导出操作,无需依赖 Microsoft Office。

要开始学习,请在 Visual Studio 中创建一个新的 Windows 窗体项目,然后在窗体中添加以下命名空间:

using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
$vbLabelText   $csharpLabel

在表单中添加一个 DataGridView 控件和一个按钮。 DataGridView 控件将在导出前显示数据,而按钮将触发导出 DataGridView 操作。

如何将数据加载到 DataGridView 控件中?

表单加载事件是将数据填充到 DataGridView 中的理想选择。 以下代码示例演示了将 DataTable 绑定到 DataGridView 控件:

private void Form1_Load(object sender, EventArgs e)
{
    // Create DataTable with sample data
    DataTable dt = new DataTable();
    dt.Columns.Add("ProductID", typeof(int));
    dt.Columns.Add("ProductName", typeof(string));
    dt.Columns.Add("Price", typeof(decimal));
    dt.Columns.Add("Stock", typeof(int));
    // Add rows with values
    dt.Rows.Add(1, "Laptop", 999.99, 50);
    dt.Rows.Add(2, "Mouse", 29.99, 200);
    dt.Rows.Add(3, "Keyboard", 79.99, 150);
    dt.Rows.Add(4, "Monitor", 349.99, 75);
    dataGridView1.DataSource = dt;
}
private void Form1_Load(object sender, EventArgs e)
{
    // Create DataTable with sample data
    DataTable dt = new DataTable();
    dt.Columns.Add("ProductID", typeof(int));
    dt.Columns.Add("ProductName", typeof(string));
    dt.Columns.Add("Price", typeof(decimal));
    dt.Columns.Add("Stock", typeof(int));
    // Add rows with values
    dt.Rows.Add(1, "Laptop", 999.99, 50);
    dt.Rows.Add(2, "Mouse", 29.99, 200);
    dt.Rows.Add(3, "Keyboard", 79.99, 150);
    dt.Rows.Add(4, "Monitor", 349.99, 75);
    dataGridView1.DataSource = dt;
}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Create DataTable with sample data
    Dim dt As New DataTable()
    dt.Columns.Add("ProductID", GetType(Integer))
    dt.Columns.Add("ProductName", GetType(String))
    dt.Columns.Add("Price", GetType(Decimal))
    dt.Columns.Add("Stock", GetType(Integer))
    ' Add rows with values
    dt.Rows.Add(1, "Laptop", 999.99D, 50)
    dt.Rows.Add(2, "Mouse", 29.99D, 200)
    dt.Rows.Add(3, "Keyboard", 79.99D, 150)
    dt.Rows.Add(4, "Monitor", 349.99D, 75)
    dataGridView1.DataSource = dt
End Sub
$vbLabelText   $csharpLabel

填充式数据表

C# DataGridView Export to Excel with Formatting:完整指南:图片 2 - 我们表单的用户界面

此代码创建了一个包含四列的 DataTable dt,然后使用 Add 方法将示例值填充到 DataGridView 行中。 DataGridView 控件接受 DataTable 作为其数据源,该数据源将以表格格式显示数据。 第一列包含整数 ID,其他列包含字符串和十进制值。

如何将 DataGridView 数据导出到 Excel 文件?

按钮点击事件处理程序包含核心导出逻辑。 IronXL 的方法与传统方法不同; DataGridView 的内容可通过 DataTable 中间步骤直接导出到 Excel 文件:

private void btnExport_Click(object sender, EventArgs e)
{
    try
    {
        // Convert DataGridView to DataTable
        DataTable dt = new DataTable();
        foreach (DataGridViewColumn column in dataGridView1.Columns)
            dt.Columns.Add(column.HeaderText);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (!row.IsNewRow)
            {
                DataRow dataRow = dt.NewRow();
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    dataRow[i] = row.Cells[i].Value;
                dt.Rows.Add(dataRow);
            }
        }
        // Create workbook and export
        WorkBook workbook = WorkBook.Create();
        WorkSheet worksheet = workbook.DefaultWorkSheet;
        worksheet.LoadFromDataTable(dt, true);
        workbook.SaveAs("C:\\Reports\\Export.xlsx");
        MessageBox.Show("Export complete!");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Error: {ex.Message}");
    }
}
private void btnExport_Click(object sender, EventArgs e)
{
    try
    {
        // Convert DataGridView to DataTable
        DataTable dt = new DataTable();
        foreach (DataGridViewColumn column in dataGridView1.Columns)
            dt.Columns.Add(column.HeaderText);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (!row.IsNewRow)
            {
                DataRow dataRow = dt.NewRow();
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    dataRow[i] = row.Cells[i].Value;
                dt.Rows.Add(dataRow);
            }
        }
        // Create workbook and export
        WorkBook workbook = WorkBook.Create();
        WorkSheet worksheet = workbook.DefaultWorkSheet;
        worksheet.LoadFromDataTable(dt, true);
        workbook.SaveAs("C:\\Reports\\Export.xlsx");
        MessageBox.Show("Export complete!");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Error: {ex.Message}");
    }
}
Private Sub btnExport_Click(sender As Object, e As EventArgs)
    Try
        ' Convert DataGridView to DataTable
        Dim dt As New DataTable()
        For Each column As DataGridViewColumn In dataGridView1.Columns
            dt.Columns.Add(column.HeaderText)
        Next
        For Each row As DataGridViewRow In dataGridView1.Rows
            If Not row.IsNewRow Then
                Dim dataRow As DataRow = dt.NewRow()
                For i As Integer = 0 To dataGridView1.Columns.Count - 1
                    dataRow(i) = row.Cells(i).Value
                Next
                dt.Rows.Add(dataRow)
            End If
        Next
        ' Create workbook and export
        Dim workbook As WorkBook = WorkBook.Create()
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
        worksheet.LoadFromDataTable(dt, True)
        workbook.SaveAs("C:\Reports\Export.xlsx")
        MessageBox.Show("Export complete!")
    Catch ex As Exception
        MessageBox.Show($"Error: {ex.Message}")
    End Try
End Sub
$vbLabelText   $csharpLabel

将 DataGridView 输出到 Excel.

C# DataGridView Export to Excel with Formatting:完整指南:图片 3 - 生成的 Excel 文件

此按钮单击事件处理程序使用 object sender, EventArgs e 参数遍历 DataGridView 行和列中的所有数据,构建 DataTableLoadFromDataTable 方法接受 DataTable 并填充工作表。 然后将工作簿对象保存到指定位置。 IronXL.Excel 还可以高效导出大型 Excel 文件,而不会出现 Microsoft Interop 常见的内存问题。

如何对导出的 Excel 文件应用格式化?

创建格式化 Excel 文件需要对标题行和单元格进行样式设计。 本示例演示了如何应用标题行背景颜色和交替行样式:

private void ExportWithFormatting(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create();
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    // Add header row
    string[] headers = { "ID", "Name", "Price", "Stock" };
    for (int col = 0; col < headers.Length; col++)
    {
        worksheet.SetCellValue(0, col, headers[col]);
        worksheet[$"{(char)('A' + col)}1"].Style.Font.Bold = true;
        worksheet[$"{(char)('A' + col)}1"].Style.SetBackgroundColor("#4472C4");
    }
    // Add data with alternating row colors
    int rowIndex = 1;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow) continue;
        for (int col = 0; col < dataGridView1.Columns.Count; col++)
        {
            worksheet.SetCellValue(rowIndex, col, row.Cells[col].Value?.ToString());
        }
        // Apply alternating background colors
        if (rowIndex % 2 == 0)
        {
            var range = worksheet[$"A{rowIndex + 1}:D{rowIndex + 1}"];
            range.Style.SetBackgroundColor("#D6DCE5");
        }
        rowIndex++;
    }
    workbook.SaveAs("C:\\Reports\\FormattedExport.xlsx");
}
private void ExportWithFormatting(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create();
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    // Add header row
    string[] headers = { "ID", "Name", "Price", "Stock" };
    for (int col = 0; col < headers.Length; col++)
    {
        worksheet.SetCellValue(0, col, headers[col]);
        worksheet[$"{(char)('A' + col)}1"].Style.Font.Bold = true;
        worksheet[$"{(char)('A' + col)}1"].Style.SetBackgroundColor("#4472C4");
    }
    // Add data with alternating row colors
    int rowIndex = 1;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow) continue;
        for (int col = 0; col < dataGridView1.Columns.Count; col++)
        {
            worksheet.SetCellValue(rowIndex, col, row.Cells[col].Value?.ToString());
        }
        // Apply alternating background colors
        if (rowIndex % 2 == 0)
        {
            var range = worksheet[$"A{rowIndex + 1}:D{rowIndex + 1}"];
            range.Style.SetBackgroundColor("#D6DCE5");
        }
        rowIndex++;
    }
    workbook.SaveAs("C:\\Reports\\FormattedExport.xlsx");
}
Private Sub ExportWithFormatting(sender As Object, e As EventArgs)
    Dim workbook As WorkBook = WorkBook.Create()
    Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
    ' Add header row
    Dim headers As String() = {"ID", "Name", "Price", "Stock"}
    For col As Integer = 0 To headers.Length - 1
        worksheet.SetCellValue(0, col, headers(col))
        worksheet($"{ChrW(AscW("A"c) + col)}1").Style.Font.Bold = True
        worksheet($"{ChrW(AscW("A"c) + col)}1").Style.SetBackgroundColor("#4472C4")
    Next
    ' Add data with alternating row colors
    Dim rowIndex As Integer = 1
    For Each row As DataGridViewRow In dataGridView1.Rows
        If row.IsNewRow Then Continue For
        For col As Integer = 0 To dataGridView1.Columns.Count - 1
            worksheet.SetCellValue(rowIndex, col, If(row.Cells(col).Value?.ToString(), String.Empty))
        Next
        ' Apply alternating background colors
        If rowIndex Mod 2 = 0 Then
            Dim range = worksheet($"A{rowIndex + 1}:D{rowIndex + 1}")
            range.Style.SetBackgroundColor("#D6DCE5")
        End If
        rowIndex += 1
    Next
    workbook.SaveAs("C:\Reports\FormattedExport.xlsx")
End Sub
$vbLabelText   $csharpLabel

格式化 Excel 文件输出

C# DataGridView Export to Excel with Formatting:完整指南:图片 4 - 生成格式化 Excel 文件的输出

此 C# DataGridView 导出到 Excel 并带有格式化示例将第一行设置为带有粗体字体和背景颜色的样式标题行。 代码采用交替行样式,以提高可读性。 您可以使用 IronXL 的综合 样式 API 使用不同的字体样式、填充图案和边框配置自定义单元格。

结论

有了 IronXL.Excel,在 Windows 窗体应用程序中将 DataGridView 导出到 Excel 变得简单易行。 与需要 COM 标签引用和复杂对象清理代码的传统 Microsoft Excel 对象库方法不同,IronXL.Excel 为创建带格式的 Excel 文件提供了简洁、现代的 API。

从基本数据到 Excel 导出,再到复杂的格式化 Excel 文件生成(包括标题行背景颜色样式和交替行),该库均可处理。 对于处理大型 Excel 文件的应用程序,IronXL.Excel 可提供卓越的性能,而无需安装 Microsoft Excel。

准备好简化您的 DataGridView 到 Excel 的工作流程了吗? 立即开始免费试用,或探索用于生产部署的 IronXL 许可选项

常见问题解答

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

使用 IronXL,您可以利用其强大的数据操作和导出功能,在 C# 中轻松地将 DataGridView 数据导出到 Excel 文件。

将 DataGridView 导出到 Excel 时有哪些格式选项?

IronXL.Excel 允许您在将 DataGridView 导出到 Excel 时应用各种格式化选项,如标题样式和交替行颜色。

能否在 Windows 窗体应用程序中将 DataGridView 数据导出到 Excel?

是的,您可以在 Windows 窗体应用程序中使用 IronXL 将 DataGridView 数据导出到 Excel,IronXL.Excel 为此提供了无缝集成和功能。

在将 DataGridView 导出到 Excel 时,能否设置标题样式?

在将 DataGridView 数据导出到 Excel 时,IronXL.Excel 可让您使用自定义字体、颜色和其他格式选项来设计标题样式。

从 DataGridView 导出时,如何在 Excel 中应用交替行颜色?

IronXL.Excel 允许您在从 DataGridView 导出数据时将交替的行颜色应用到 Excel 表单中,从而增强数据的视觉吸引力和可读性。

用 C# 将 DataGridView 导出到 Excel 需要特殊的库吗?

是的,使用 IronXL 这样的库简化了在 C# 中将 DataGridView 导出到 Excel 的过程,为数据处理和格式化提供了强大的工具。

使用 IronXL 将 DataGridView 导出到 Excel 有哪些好处?

IronXL.Excel 具有使用方便、格式选项全面以及与 Windows 窗体兼容等优点,是将 DataGridView 导出到 Excel 的理想工具。

Curtis Chau
技术作家

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

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