跳至页脚内容
使用 IRONXL

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

使用IronXL时,将数据从 DataGridView 导出到 Excel 文件只需要几行 C# 代码。 创建一个 WorkBook,遍历网格的列和行,将每个单元格的值写入工作表,然后调用 SaveAs 生成一个完全格式化的 .xlsx 文件 -- 无需安装 Microsoft Office。

如何为 Excel 导出设置 Windows Forms 项目?

Windows Forms 是 .NET 生态系统中一个基础的 GUI 库,广泛用于构建桌面应用程序。 DataGridView 控件是其最常用的组件之一:它可以显示、编辑和管理来自任何可绑定源(例如 DataTable、数据库查询结果或内存列表)的表格数据。

将网格数据导出到 Excel 可满足多种日常需求——向利益相关者发送报告、存档快照以备审计,或将数据导入下游分析工具。 两种传统方法是 Microsoft Office Interop 和第三方库。 Interop 要求在每台运行该应用程序的机器上安装 Excel,这会导致 COM 对象生命周期问题,且在服务器或云部署环境中性能不佳。 IronXL、ClosedXML 和 Syncfusion 等库通过直接写入 Open XML 文件格式,且不依赖 Office,从而避免了这些问题。

本指南演示了 IronXL 在 C# 中的应用,目标平台为 .NET 10,不过 IronXL 也支持 .NET Framework 4.6.2 及所有现代 .NET 版本

前提条件

在编写任何导出代码之前,请确认以下条件已满足:

  • Visual Studio 2022 或更高版本 已安装.NET 10 SDK
  • 一个包含 DataGridView 控件的 Windows 窗体应用程序项目 -NuGet访问来安装IronXL

如何安装 IronXL?

在 Visual Studio 中打开"包管理器控制台",并运行以下任一命令:

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

或者,在解决方案资源管理器中右键单击项目,选择"管理 NuGet 程序包" ,搜索 IronXL.Excel,然后单击"安装"

!a href="/static-assets/excel/blog/export-datagridview-vb-net-2010/export-datagridview-vb-net-2010-1.webp">Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 1 - Installation(使用 IronXL.Excel 在 VB .NET 2010 中将数据从 DataGridView 导出到 Excel)。

安装完成后,请在使用 Excel 功能的任何文件顶部添加 IronXL 的 using 指令:

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

IronXL 支持所有常见的电子表格格式:XLSX、XLS、CSV 和 TSV。 本指南通篇使用 XLSX 格式,因为这是现代 Excel 版本的默认格式。

如何向 DataGridView 填充示例数据?

在本演练中,表单包含一个名为 DataGridViewDataGridView1 和一个名为 btnExport 的按钮。 表格在表单的 Load 事件中填充,员工记录存储在 DataTable 中:

void Form1_Load(object sender, EventArgs e)
{
    var dt = new DataTable();

    // Define columns with the appropriate .NET type
    dt.Columns.Add("EmployeeID", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Department", typeof(string));
    dt.Columns.Add("Salary", typeof(decimal));

    // Add sample rows
    dt.Rows.Add(101, "Sarah Johnson", "Engineering", 85000m);
    dt.Rows.Add(102, "Michael Chen", "Marketing", 72000m);
    dt.Rows.Add(103, "Emily Davis", "Finance", 91000m);
    dt.Rows.Add(104, "James Wilson", "Engineering", 78000m);

    DataGridView1.DataSource = dt;
}
void Form1_Load(object sender, EventArgs e)
{
    var dt = new DataTable();

    // Define columns with the appropriate .NET type
    dt.Columns.Add("EmployeeID", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Department", typeof(string));
    dt.Columns.Add("Salary", typeof(decimal));

    // Add sample rows
    dt.Rows.Add(101, "Sarah Johnson", "Engineering", 85000m);
    dt.Rows.Add(102, "Michael Chen", "Marketing", 72000m);
    dt.Rows.Add(103, "Emily Davis", "Finance", 91000m);
    dt.Rows.Add(104, "James Wilson", "Engineering", 78000m);

    DataGridView1.DataSource = dt;
}
Option Strict On



Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As New DataTable()

    ' Define columns with the appropriate .NET type
    dt.Columns.Add("EmployeeID", GetType(Integer))
    dt.Columns.Add("Name", GetType(String))
    dt.Columns.Add("Department", GetType(String))
    dt.Columns.Add("Salary", GetType(Decimal))

    ' Add sample rows
    dt.Rows.Add(101, "Sarah Johnson", "Engineering", 85000D)
    dt.Rows.Add(102, "Michael Chen", "Marketing", 72000D)
    dt.Rows.Add(103, "Emily Davis", "Finance", 91000D)
    dt.Rows.Add(104, "James Wilson", "Engineering", 78000D)

    DataGridView1.DataSource = dt
End Sub
$vbLabelText   $csharpLabel

每列都定义了特定的 .NET 类型,以确保后续的数值比较和格式化操作能够正确进行。 DataSource 属性将 DataTable 直接绑定到 DataGridView,表单打开时,网格会自动呈现所有行。 在实际生产环境中,此类数据通常来自数据库查询、ORM 结果集或 REST API 响应,而非硬编码的值。

!a href="/static-assets/excel/blog/export-datagridview-vb-net-2010/export-datagridview-vb-net-2010-2.webp">Export DataGridView from Excel to Excel in VB .NET 2010 Using IronXL: Image 2 - DataGridView Output

理解 DataGridView 数据模型

A DataGridView 通过两个集合公开其内容:Columns(用于元数据,例如 HeaderText 和列索引)和 Rows(用于实际数据单元格)。 每个 DataGridViewRow 包含一个按列位置索引的 Cells 集合。 每个单元格的 Value 属性返回一个装箱对象,必须先将其强制转换或转换,然后才能将其写入 Excel 单元格。 理解这一层次结构对于编写可靠的导出循环至关重要。

DataTable 在后台存储键入的值,因此十进制工资在写入 IronXL 工作表之前不需要字符串转换。 IronXL 的 SetCellValue 方法接受 stringdoubledecimalintboolDateTime 重载,允许您在输出文件中保留原始数据类型。

如何将 DataGridView 数据导出到带有列标题的 Excel 文件中?

导出逻辑位于按钮的点击处理程序中。 该代码创建一个新的工作表,检索默认工作表,将列标题写入第一行,然后将每一行数据写入列标题下方:

void btnExport_Click(object sender, EventArgs e)
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    // Write column headers to row index 0
    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    // Write data rows starting at row index 1
    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cellValue = DataGridView1.Rows[row].Cells[col].Value;
            if (cellValue is not null)
            {
                sheet.SetCellValue(row + 1, col, cellValue.ToString()!);
            }
        }
    }

    string outputPath = "EmployeeData.xlsx";
    workbook.SaveAs(outputPath);
    MessageBox.Show("Export complete. File saved to: " + outputPath, "Success");
}
void btnExport_Click(object sender, EventArgs e)
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    // Write column headers to row index 0
    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    // Write data rows starting at row index 1
    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cellValue = DataGridView1.Rows[row].Cells[col].Value;
            if (cellValue is not null)
            {
                sheet.SetCellValue(row + 1, col, cellValue.ToString()!);
            }
        }
    }

    string outputPath = "EmployeeData.xlsx";
    workbook.SaveAs(outputPath);
    MessageBox.Show("Export complete. File saved to: " + outputPath, "Success");
}
Private Sub btnExport_Click(sender As Object, e As EventArgs)
    Dim workbook = WorkBook.Create()
    Dim sheet = workbook.DefaultWorkSheet

    ' Write column headers to row index 0
    For col As Integer = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, col, DataGridView1.Columns(col).HeaderText)
    Next

    ' Write data rows starting at row index 1
    For row As Integer = 0 To DataGridView1.Rows.Count - 1
        For col As Integer = 0 To DataGridView1.Columns.Count - 1
            Dim cellValue As Object = DataGridView1.Rows(row).Cells(col).Value
            If cellValue IsNot Nothing Then
                sheet.SetCellValue(row + 1, col, cellValue.ToString())
            End If
        Next
    Next

    Dim outputPath As String = "EmployeeData.xlsx"
    workbook.SaveAs(outputPath)
    MessageBox.Show("Export complete. File saved to: " & outputPath, "Success")
End Sub
$vbLabelText   $csharpLabel

WorkBook 对象在内存中表示整个 Excel 文件。 DefaultWorkSheet 返回第一个工作表,而无需您显式创建工作表。 外层循环将 HeaderText 中的标题文本写入第 0 行。 随后,嵌套循环将遍历每一行数据,在将单元格值转换为字符串之前先检查其是否为空。 row + 1 偏移量将数据移到标题行下方。 SaveAs 将完成的工作簿以Open XML XLSX 文件的形式写入指定路径。

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 3 - Excel Output

生成的文件可在 Excel、Google 表格或任何支持 XLSX 格式的应用程序中打开。 列标题出现在第一行,所有数据行都按照它们在 DataGridView 中出现的顺序排列。

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

单纯的数据转录虽能满足功能需求,但尚不具备展示效果。 IronXL 的样式 API 允许您在保存前对任意单元格区域应用粗体字体、背景色、文字颜色和数字格式:

void ExportWithFormatting()
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    // Write column headers
    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    // Style the header row: bold white text on blue background
    var headerRange = sheet.GetRange("A1:D1");
    headerRange.Style.Font.Bold = true;
    headerRange.Style.SetBackgroundColor("#4472C4");
    headerRange.Style.Font.SetColor("#FFFFFF");

    // Locate the Salary column index
    int salaryColIndex = -1;
    for (int i = 0; i < DataGridView1.Columns.Count; i++)
    {
        if (string.Equals(DataGridView1.Columns[i].HeaderText, "Salary",
            StringComparison.OrdinalIgnoreCase))
        {
            salaryColIndex = i;
            break;
        }
    }

    // Write data rows, preserving numeric types
    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        if (DataGridView1.Rows[row].IsNewRow) continue;

        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cellValue = DataGridView1.Rows[row].Cells[col].Value;
            if (cellValue is null) continue;

            int targetRow = row + 1;

            if (col == salaryColIndex)
            {
                // Write salary as a true numeric decimal
                if (decimal.TryParse(cellValue.ToString(),
                    System.Globalization.NumberStyles.Number,
                    System.Globalization.CultureInfo.InvariantCulture,
                    out decimal decValue))
                {
                    sheet.SetCellValue(targetRow, col, decValue);
                }
                else
                {
                    sheet.SetCellValue(targetRow, col, cellValue.ToString()!);
                }
            }
            else
            {
                sheet.SetCellValue(targetRow, col, cellValue.ToString()!);
            }
        }
    }

    // Apply currency format to the salary column data range
    var salaryRange = sheet.GetRange("D2:D5");
    salaryRange.FormatString = "$#,##0";

    workbook.SaveAs("FormattedEmployeeData.xlsx");
}
void ExportWithFormatting()
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    // Write column headers
    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    // Style the header row: bold white text on blue background
    var headerRange = sheet.GetRange("A1:D1");
    headerRange.Style.Font.Bold = true;
    headerRange.Style.SetBackgroundColor("#4472C4");
    headerRange.Style.Font.SetColor("#FFFFFF");

    // Locate the Salary column index
    int salaryColIndex = -1;
    for (int i = 0; i < DataGridView1.Columns.Count; i++)
    {
        if (string.Equals(DataGridView1.Columns[i].HeaderText, "Salary",
            StringComparison.OrdinalIgnoreCase))
        {
            salaryColIndex = i;
            break;
        }
    }

    // Write data rows, preserving numeric types
    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        if (DataGridView1.Rows[row].IsNewRow) continue;

        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cellValue = DataGridView1.Rows[row].Cells[col].Value;
            if (cellValue is null) continue;

            int targetRow = row + 1;

            if (col == salaryColIndex)
            {
                // Write salary as a true numeric decimal
                if (decimal.TryParse(cellValue.ToString(),
                    System.Globalization.NumberStyles.Number,
                    System.Globalization.CultureInfo.InvariantCulture,
                    out decimal decValue))
                {
                    sheet.SetCellValue(targetRow, col, decValue);
                }
                else
                {
                    sheet.SetCellValue(targetRow, col, cellValue.ToString()!);
                }
            }
            else
            {
                sheet.SetCellValue(targetRow, col, cellValue.ToString()!);
            }
        }
    }

    // Apply currency format to the salary column data range
    var salaryRange = sheet.GetRange("D2:D5");
    salaryRange.FormatString = "$#,##0";

    workbook.SaveAs("FormattedEmployeeData.xlsx");
}
Option Strict On



Sub ExportWithFormatting()
    Dim workbook = WorkBook.Create()
    Dim sheet = workbook.DefaultWorkSheet

    ' Write column headers
    For col As Integer = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, col, DataGridView1.Columns(col).HeaderText)
    Next

    ' Style the header row: bold white text on blue background
    Dim headerRange = sheet.GetRange("A1:D1")
    headerRange.Style.Font.Bold = True
    headerRange.Style.SetBackgroundColor("#4472C4")
    headerRange.Style.Font.SetColor("#FFFFFF")

    ' Locate the Salary column index
    Dim salaryColIndex As Integer = -1
    For i As Integer = 0 To DataGridView1.Columns.Count - 1
        If String.Equals(DataGridView1.Columns(i).HeaderText, "Salary", StringComparison.OrdinalIgnoreCase) Then
            salaryColIndex = i
            Exit For
        End If
    Next

    ' Write data rows, preserving numeric types
    For row As Integer = 0 To DataGridView1.Rows.Count - 1
        If DataGridView1.Rows(row).IsNewRow Then Continue For

        For col As Integer = 0 To DataGridView1.Columns.Count - 1
            Dim cellValue As Object = DataGridView1.Rows(row).Cells(col).Value
            If cellValue Is Nothing Then Continue For

            Dim targetRow As Integer = row + 1

            If col = salaryColIndex Then
                ' Write salary as a true numeric decimal
                Dim decValue As Decimal
                If Decimal.TryParse(cellValue.ToString(), Globalization.NumberStyles.Number, Globalization.CultureInfo.InvariantCulture, decValue) Then
                    sheet.SetCellValue(targetRow, col, decValue)
                Else
                    sheet.SetCellValue(targetRow, col, cellValue.ToString())
                End If
            Else
                sheet.SetCellValue(targetRow, col, cellValue.ToString())
            End If
        Next
    Next

    ' Apply currency format to the salary column data range
    Dim salaryRange = sheet.GetRange("D2:D5")
    salaryRange.FormatString = "$#,##0"

    workbook.SaveAs("FormattedEmployeeData.xlsx")
End Sub
$vbLabelText   $csharpLabel

GetRange 方法接受标准 Excel 表示法 (A1:D1) 来选择连续的单元格块。 设置 Style.Font.BoldStyle.SetBackgroundColorStyle.Font.SetColor 会将这些格式应用于所选范围内的每个单元格。 对于数值列,将值写入 decimal 而不是字符串可以保持数据类型不变,这意味着 Excel 可以正确应用数字格式,例如 $#,##0。 以字符串形式存储的单元格不响应数字格式代码。

Export DataGridView to Excel in VB .NET 2010 Using IronXL: Image 4 - Formatted Excel Output.

您可参考 IronXL 样式文档,将此模式扩展应用于交替行填充、列宽自动调整或冻结窗格等功能。

如何将 DataGridView 数据导出为 CSV 而不是 XLSX?

某些工作流需要 CSV 输出,以兼容旧系统或轻量级数据管道。 IronXL 支持 CSV 导出,且无需对主代码进行任何额外配置更改:

void ExportToCsv()
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        if (DataGridView1.Rows[row].IsNewRow) continue;

        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cell = DataGridView1.Rows[row].Cells[col].Value;
            if (cell is not null)
                sheet.SetCellValue(row + 1, col, cell.ToString()!);
        }
    }

    // Saving with a .csv extension produces a comma-separated file
    workbook.SaveAs("EmployeeData.csv");
}
void ExportToCsv()
{
    var workbook = WorkBook.Create();
    var sheet = workbook.DefaultWorkSheet;

    for (int col = 0; col < DataGridView1.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, DataGridView1.Columns[col].HeaderText);
    }

    for (int row = 0; row < DataGridView1.Rows.Count; row++)
    {
        if (DataGridView1.Rows[row].IsNewRow) continue;

        for (int col = 0; col < DataGridView1.Columns.Count; col++)
        {
            object? cell = DataGridView1.Rows[row].Cells[col].Value;
            if (cell is not null)
                sheet.SetCellValue(row + 1, col, cell.ToString()!);
        }
    }

    // Saving with a .csv extension produces a comma-separated file
    workbook.SaveAs("EmployeeData.csv");
}
Sub ExportToCsv()
    Dim workbook = WorkBook.Create()
    Dim sheet = workbook.DefaultWorkSheet

    For col As Integer = 0 To DataGridView1.Columns.Count - 1
        sheet.SetCellValue(0, col, DataGridView1.Columns(col).HeaderText)
    Next

    For row As Integer = 0 To DataGridView1.Rows.Count - 1
        If DataGridView1.Rows(row).IsNewRow Then Continue For

        For col As Integer = 0 To DataGridView1.Columns.Count - 1
            Dim cell As Object = DataGridView1.Rows(row).Cells(col).Value
            If cell IsNot Nothing Then
                sheet.SetCellValue(row + 1, col, cell.ToString())
            End If
        Next
    Next

    ' Saving with a .csv extension produces a comma-separated file
    workbook.SaveAs("EmployeeData.csv")
End Sub
$vbLabelText   $csharpLabel

与 XLSX 导出相比,唯一的变化是传递给 SaveAs 的文件扩展名。 IronXL 会自动检测文件扩展名,并以正确的格式序列化工作簿。 这种一致性意味着,无论输出格式如何,您的数据写入逻辑始终保持不变——这相较于那些需要为每种格式单独编写代码路径的库而言,具有显著优势。

当下游用户是 Python pandas 脚本、数据库批量导入工具或无法读取二进制 XLSX 文件的分析平台时,CSV 导出功能尤为实用。

如何高效处理大型 DataGridView 数据集?

对于包含数万行数据的网格,性能便成为需要考虑的因素。 以下模式通过单次遍历构建完整数据集,从而减轻内存压力:

IronXL 针对大型数据集的导出方法对比
方法 已处理的行 办公室要求 保留原文格式
Microsoft.Office.Interop.Excel 最多 ~65k(速度较慢) 部分的
IronXL(字符串单元格) 100 多万行 无(所有文本)
IronXL(带数据类型的单元格) 100 多万行
从 DataTable 转换为 IronXL 100 多万行 是(自动)

DataGridView 绑定到 DataTable 时,您可以使用WorkSheet.LoadDataTable方法直接将表格加载到 IronXL 中,完全绕过逐个单元格的迭代。 这种方法速度更快,并且能自动保留所有列类型。

对于没有 DataTable 支持的网格,前面所示的逐个单元格模式仍然是标准方法。 如果您需要异步导出以在大型导出期间保持 UI 的响应性,请将导出逻辑包装在 Task.Run 调用中,并在后台线程上 await 结果。 请参阅异步文件操作文档,了解将结果回传至 UI 线程的实现模式。

为何 IronXL 在 DataGridView 导出方面优于 Office Interop?

传统的 .NET 解决方案使用 Microsoft.Office.Interop.Excel 来驱动正在运行的 Excel 进程。 这种做法会引发若干部署和可靠性问题:

  • 每台运行该应用程序的计算机都需要安装一份已授权的 Microsoft Excel 副本
  • 服务器环境和云容器通常无法安装 Office
  • COM 互操作性要求显式释放每个对象,以避免内存泄漏和僵尸 Excel 进程
  • 跨 COM 边界的错误处理既冗长又脆弱
  • 随着行数增加,性能会迅速下降

IronXL 直接写入 OOXML 文件格式,无需启动任何外部进程。 应用程序以自包含单元形式部署。 该库的 API 是完全托管的 .NET,因此垃圾回收会自动处理内存,无需 Marshal.ReleaseComObject 调用。 由于无需进行进程间通信,运行速度显著提升。

对于正在评估替代方案的团队而言,ClosedXML 是一个广受欢迎的开源选项。 IronXL 提供更全面的功能集,包括 PDF 转换图表生成和商业支持,这些可能是 Enterprise 采购决策的考量因素。 请查看 IronXL许可选项,根据您的团队规模和部署场景选择合适的许可层级。

功能对比:IronXL 与 Office Interop
特征 IronXL Office Interop
需要安装办公软件
服务器/云部署 否(不支持)
托管内存模型 不需要(COM清理)
XLSX / CSV / XLS 格式 以上三款 取决于已安装的 Excel
从电子表格导出 PDF 需要额外库

IronXL 教程部分涵盖了读取现有 Excel 文件、修改模板、生成图表以及应用条件格式化等内容——所有这些功能都是基于此处展示的 DataGridView 导出模式自然延伸而来的。

下一步计划是什么?

您现在拥有可以使用 IronXL 将 DataGridView 导出到格式化 Excel 文件的工作 C# 代码。 在此基础上,请参考以下翻译方向:

-添加错误处理:将导出代码包裹在 try/catch 代码块中,并在文件被锁定或路径无效时显示用户友好的消息。 -支持文件路径选择:使用 SaveFileDialog 允许用户在运行时选择输出位置和文件名。 -加载真实数据:将示例代码 DataTable 替换为使用ADO.NET或 Entity Framework 的数据库查询。

  • 读取现有文件:使用 WorkBook.Load 打开现有电子表格并进行更新,而非总是创建新文件 -导出到多个工作表:在同一个工作表中创建额外的对象,以组织相关的数据集
  • 应用条件格式:使用 IronXL 的条件格式 API 突出显示超过阈值的单元格
  • 查看许可选项:提供免费试用许可证; 许可层级涵盖从个人开发者到Enterprise部署
  • 浏览完整的 API 参考文档IronXL 对象参考文档详细记录了所有可用的类和方法

常见问题解答

在 C# 中,将 DataGridView 数据导出到 Excel 的最简单方法是什么?

使用IronXL,您可以通过一个简单的 C# 循环将 DataGridView 数据导出到 Excel。该循环会将列标题和数据行写入 WorkBook 对象,然后调用 SaveAs 函数生成 XLSX 文件。无需安装 Microsoft Office。

如何在 C# Windows Forms 应用程序中使用IronXL处理 Excel 文件?

通过NuGet安装IronXL ,添加 using IronXL指令,使用 WorkBook.Create() 创建工作簿,使用 SetCellValue 写入数据,并使用 SaveAs 保存。IronXL 支持IronXL 、XLS 和 CSV 格式。

IronXL.Excel 是否支持将大型 DataGridView 数据集导出到 Excel?

是的, IronXL可以高效地处理大型数据集。对于由 DataTable 支持的 DataGridView,您可以使用 LoadDataTable 方法绕过逐个单元格的迭代,从而获得更佳的性能。

使用IronXL需要安装 Microsoft Excel 吗?

不IronXL直接写入 Open XML 文件格式,无需启动 Excel 或任何 COM 自动化程序。使用IronXL构建的应用程序可以部署到没有 Office 的服务器和云环境中。

与 Office Interop 相比,使用IronXL进行 Excel 导出有哪些优势?

IronXL无需安装 Office,避免了 COM 内存泄漏问题,支持服务器和云部署,并提供简洁的托管.NET API 用于读取和写入 XLSX、XLS 和 CSV 文件。

IronXL能否将 DataGridView 数据导出为 CSV 和 XLSX 格式?

是的。将 .csv 文件路径传递给 WorkBook.SaveAs 会生成一个逗号分隔的文件。两种格式的数据写入代码完全相同——只有文件扩展名不同。

如何使用IronXL对导出的 Excel 单元格应用格式?

使用 WorkSheet.GetRange 选择单元格区域,然后访问 Style 属性来设置 Font.Bold、SetBackgroundColor、Font.SetColor 和 FormatString 以设置数字格式。

如何在 C# 项目中开始使用IronXL ?

在您的项目中运行Install-Package IronXL或 dotnet add package IronXL ,在文件顶部添加 using IronXL ,并按照 ironsoftware.com/csharp/excel/ 上的IronXL文档中的示例进行操作。

Curtis Chau
技术作家

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

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

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我