跳至頁尾內容
USING IRONXL

C# DataGridView 匯出到 Excel:完整格式指南 | IronXL

C# DataGridView導出到Excel並格式化:完整指南:圖片1 - C# DataGridView導出到Excel並格式化

DataGridView資料導出到Excel文件是Windows窗體開發中最常見的任務之一。 在建立顯示表格資料的商業應用程式中——無論是銷售報告、庫存記錄、或客戶名單——使用者期望可以點擊一個按鈕,接收一個格式正確的Excel檔案供分享或進一步分析。 挑戰在於如何清晰地做到這一點,而不依賴於每台終端使用者機上安裝Microsoft Excel,也不用處理COM互操作清理程式碼引起的記憶體洩漏或靜默崩潰。 本指南將引導您完成使用IronXL在C#中導出DataGridView到Excel的完整流程,涵蓋從專案設置到高級單元格式化的所有內容,最終讓您擁有可投入生產的程式碼。

現在開始使用IronXL。
green arrow pointer

如何設置Windows窗體專案以進行DataGridView導出?

傳統的DataGridView資料導出方法依賴Microsoft互操作——您需要打開新增引用,導航到COM選項卡,選擇Microsoft Excel物件庫,並編寫易碎的程式碼來調用Marshal.ReleaseComObject以避免記憶體洩漏。 此模式要求在應用程式運行的每台計算機上安裝Microsoft Excel,在處理大型資料集時表現緩慢,並且在缺乏Office授權的部署環境中經常產生COMException錯誤。 Microsoft對Office自動化的指導明確建議在伺服器端和自動化場景中使用第三方程式庫。

IronXL可移除所有這些相依性。 這是一個純.NET程式庫,可以讀寫.ods檔案,而無需Microsoft Office或任何COM註冊。 您通過NuGet安裝它並立即開始編寫程式碼。

通過NuGet安裝IronXL

首先在Visual Studio中建立一個新的Windows Forms應用專案,目標為.NET 10。在表單介面新增一個Button。 將按鈕命名為btnExport,並給它新增標籤"導出到Excel"。 然後打開NuGet Package Manager Console並運行:

Install-Package IronXL.Excel

在表格文件的頂部新增所需的名稱空間:

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

這兩個名稱空間涵蓋了您讀寫Excel工作簿所需要的所有IronXL型別,並且標準DataGridView物件。

如何將範例資料載入到DataGridView控件中?

在構建導出邏輯之前,請用代表性資料填充您的DataGridViewDataTable綁定為資料源的合適位置。 在實際應用程式中,您會查詢資料庫或調用服務;在此,硬編碼的DataTable清楚地展示了結構。 Microsoft Docs上的DataGridView控件概述提供有關控件如何管理資料源的其他背景知識。

將DataTable綁定到DataGridView

void Form1_Load(object sender, EventArgs e)
{
    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));

    dt.Rows.Add(1, "Laptop", 999.99m, 50);
    dt.Rows.Add(2, "Mouse", 29.99m, 200);
    dt.Rows.Add(3, "Keyboard", 79.99m, 150);
    dt.Rows.Add(4, "Monitor", 349.99m, 75);
    dt.Rows.Add(5, "Webcam", 89.99m, 120);

    dataGridView1.DataSource = dt;
}
void Form1_Load(object sender, EventArgs e)
{
    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));

    dt.Rows.Add(1, "Laptop", 999.99m, 50);
    dt.Rows.Add(2, "Mouse", 29.99m, 200);
    dt.Rows.Add(3, "Keyboard", 79.99m, 150);
    dt.Rows.Add(4, "Monitor", 349.99m, 75);
    dt.Rows.Add(5, "Webcam", 89.99m, 120);

    dataGridView1.DataSource = dt;
}
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    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))

    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)
    dt.Rows.Add(5, "Webcam", 89.99D, 120)

    dataGridView1.DataSource = dt
End Sub
$vbLabelText   $csharpLabel

此程式碼使用頂級語句樣式作為事件處理程式簽名。 DataTable中有四個型別化的列——整數、字串、小數和整數——IronXL在寫入Excel工作簿時會保留這些列。 型別化列之所以重要,是因為IronXL將數字列作為數字單元格寫入而非文字,讓使用者可以在Excel中排序和求和值而無需重新格式化。

C# DataGridView導出到Excel並格式化:完整指南:圖片2 - 表單的UI

DataTable列名中渲染出一個列標題行。 當您導出時,您希望在Excel檔中保留該標題行,這意味著您的導出程式碼必須分別處理標題和資料行——下一部分將具體介紹這一點。

對於生產環境使用,無論DataTable是來自Entity Framework、Dapper、ADO.NET還是任何其他資料存取層,均適用相同模式。 DataGridView綁定與導出程式碼分離,因此您可以在不觸及導出邏輯的情況下更換資料源。

如何將DataGridView資料導出到Excel檔案?

核心導出邏輯運行在按鈕點擊處理程式內。 IronXL提供一個WorkSheet上自動處理列到單元格的映射。 最乾淨的方法是從DataTable並直接傳遞。 支持.xlsx格式的Open XML SDK由Microsoft文件記載,並確認為什麼像IronXL這樣的純.NET解決方案在程式生成中表現優於互操作。

按鈕點擊導出處理程式

void btnExport_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = new DataTable();

        foreach (DataGridViewColumn column in dataGridView1.Columns)
            dt.Columns.Add(column.HeaderText);

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) continue;

            DataRow dataRow = dt.NewRow();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
                dataRow[i] = row.Cells[i].Value ?? DBNull.Value;

            dt.Rows.Add(dataRow);
        }

        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.DefaultWorkSheet;
        worksheet.Name = "Product Data";

        worksheet.LoadFromDataTable(dt, true);

        string outputPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "DataGridViewExport.xlsx"
        );

        workbook.SaveAs(outputPath);
        MessageBox.Show($"Exported successfully to:\n{outputPath}", "Export Complete",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Export failed: {ex.Message}", "Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
void btnExport_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = new DataTable();

        foreach (DataGridViewColumn column in dataGridView1.Columns)
            dt.Columns.Add(column.HeaderText);

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) continue;

            DataRow dataRow = dt.NewRow();
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
                dataRow[i] = row.Cells[i].Value ?? DBNull.Value;

            dt.Rows.Add(dataRow);
        }

        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.DefaultWorkSheet;
        worksheet.Name = "Product Data";

        worksheet.LoadFromDataTable(dt, true);

        string outputPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "DataGridViewExport.xlsx"
        );

        workbook.SaveAs(outputPath);
        MessageBox.Show($"Exported successfully to:\n{outputPath}", "Export Complete",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Export failed: {ex.Message}", "Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
Imports System
Imports System.Data
Imports System.IO
Imports System.Windows.Forms

Public Sub btnExport_Click(sender As Object, e As EventArgs)
    Try
        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 row.IsNewRow Then Continue For

            Dim dataRow As DataRow = dt.NewRow()
            For i As Integer = 0 To dataGridView1.Columns.Count - 1
                dataRow(i) = If(row.Cells(i).Value, DBNull.Value)
            Next

            dt.Rows.Add(dataRow)
        Next

        Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
        Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
        worksheet.Name = "Product Data"

        worksheet.LoadFromDataTable(dt, True)

        Dim outputPath As String = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "DataGridViewExport.xlsx"
        )

        workbook.SaveAs(outputPath)
        MessageBox.Show($"Exported successfully to:{Environment.NewLine}{outputPath}", "Export Complete",
                        MessageBoxButtons.OK, MessageBoxIcon.Information)
    Catch ex As Exception
        MessageBox.Show($"Export failed: {ex.Message}", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
$vbLabelText   $csharpLabel

C# DataGridView導出到Excel並格式化:完整指南:圖片3 - 生成的Excel檔案

DataTable和一個布林標誌,告訴IronXL將列名稱寫為第一個Excel行——這些成為您的標題單元。 工作簿保存到使用者的桌面上使用Environment.SpecialFolder.Desktop而不是硬編碼路徑,使得程式碼在使用者帳戶之間具有可移植性。

null檢查(?? DBNull.Value) prevents a NullReferenceException)當單元格不含值時出現。 對於現實世界的數據來說這很重要,因為可選字段可能是空的。 IronXL將DBNull`寫為空單元而非字串"DBNull",因此輸出保持乾淨。

有關從Excel文件中讀回資料到DataGridView的更多細節,可以參考<IronXL DataTable文件,這個文件涵蓋了逆向操作以及如何將Excel轉換爲DataSet以用於多工作表工作簿。

如何對導出的Excel文件進行專業格式化?

Excel文件中的純資料是有效的,但是專業格式化的輸出——包括加粗的標題、適合內容的列寬、交替行的背景顏色——使工具和使用者之間的信任度有了區別,避免使用者導出後立即手動重新格式化。 IronXL提供了豐富的單元樣式API,涵蓋字體、顏色、邊框、數字格式和對齊方式。 使用IronXL書寫的OOXML格式表格樣式規範由文件定義,爲您提供信心,確保輸出可以在任何相容應用程式中正確打開。

應用標題樣式和交替行顏色

void ExportWithFormatting(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    worksheet.Name = "Formatted Export";

    string[] headers = { "ID", "Product Name", "Price", "Stock" };

    // Write and style header row
    for (int col = 0; col < headers.Length; col++)
    {
        char colLetter = (char)('A' + col);
        string cellAddress = $"{colLetter}1";

        worksheet.SetCellValue(0, col, headers[col]);
        worksheet[cellAddress].Style.Font.Bold = true;
        worksheet[cellAddress].Style.Font.Height = 12;
        worksheet[cellAddress].Style.SetBackgroundColor("#4472C4");
        worksheet[cellAddress].Style.Font.Color = "#FFFFFF";
        worksheet[cellAddress].Style.HorizontalAlignment =
            IronXL.Styles.HorizontalAlignment.Center;
    }

    // Write data rows with alternating background 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() ?? string.Empty);
        }

        if (rowIndex % 2 == 0)
        {
            string rangeAddress = $"A{rowIndex + 1}:D{rowIndex + 1}";
            worksheet[rangeAddress].Style.SetBackgroundColor("#D6DCE5");
        }

        rowIndex++;
    }

    // Format the Price column as currency
    worksheet["C2:C100"].Style.Format = "$#,##0.00";

    // Auto-fit column widths
    worksheet.AutoSizeColumn(0);
    worksheet.AutoSizeColumn(1);
    worksheet.AutoSizeColumn(2);
    worksheet.AutoSizeColumn(3);

    string outputPath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "FormattedExport.xlsx"
    );

    workbook.SaveAs(outputPath);
    MessageBox.Show("Formatted export complete.", "Done",
        MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void ExportWithFormatting(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    worksheet.Name = "Formatted Export";

    string[] headers = { "ID", "Product Name", "Price", "Stock" };

    // Write and style header row
    for (int col = 0; col < headers.Length; col++)
    {
        char colLetter = (char)('A' + col);
        string cellAddress = $"{colLetter}1";

        worksheet.SetCellValue(0, col, headers[col]);
        worksheet[cellAddress].Style.Font.Bold = true;
        worksheet[cellAddress].Style.Font.Height = 12;
        worksheet[cellAddress].Style.SetBackgroundColor("#4472C4");
        worksheet[cellAddress].Style.Font.Color = "#FFFFFF";
        worksheet[cellAddress].Style.HorizontalAlignment =
            IronXL.Styles.HorizontalAlignment.Center;
    }

    // Write data rows with alternating background 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() ?? string.Empty);
        }

        if (rowIndex % 2 == 0)
        {
            string rangeAddress = $"A{rowIndex + 1}:D{rowIndex + 1}";
            worksheet[rangeAddress].Style.SetBackgroundColor("#D6DCE5");
        }

        rowIndex++;
    }

    // Format the Price column as currency
    worksheet["C2:C100"].Style.Format = "$#,##0.00";

    // Auto-fit column widths
    worksheet.AutoSizeColumn(0);
    worksheet.AutoSizeColumn(1);
    worksheet.AutoSizeColumn(2);
    worksheet.AutoSizeColumn(3);

    string outputPath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "FormattedExport.xlsx"
    );

    workbook.SaveAs(outputPath);
    MessageBox.Show("Formatted export complete.", "Done",
        MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Option Strict On



Sub ExportWithFormatting(sender As Object, e As EventArgs)
    Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
    Dim worksheet As WorkSheet = workbook.DefaultWorkSheet
    worksheet.Name = "Formatted Export"

    Dim headers As String() = {"ID", "Product Name", "Price", "Stock"}

    ' Write and style header row
    For col As Integer = 0 To headers.Length - 1
        Dim colLetter As Char = ChrW(AscW("A"c) + col)
        Dim cellAddress As String = $"{colLetter}1"

        worksheet.SetCellValue(0, col, headers(col))
        worksheet(cellAddress).Style.Font.Bold = True
        worksheet(cellAddress).Style.Font.Height = 12
        worksheet(cellAddress).Style.SetBackgroundColor("#4472C4")
        worksheet(cellAddress).Style.Font.Color = "#FFFFFF"
        worksheet(cellAddress).Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center
    Next

    ' Write data rows with alternating background 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

        If rowIndex Mod 2 = 0 Then
            Dim rangeAddress As String = $"A{rowIndex + 1}:D{rowIndex + 1}"
            worksheet(rangeAddress).Style.SetBackgroundColor("#D6DCE5")
        End If

        rowIndex += 1
    Next

    ' Format the Price column as currency
    worksheet("C2:C100").Style.Format = "$#,##0.00"

    ' Auto-fit column widths
    worksheet.AutoSizeColumn(0)
    worksheet.AutoSizeColumn(1)
    worksheet.AutoSizeColumn(2)
    worksheet.AutoSizeColumn(3)

    Dim outputPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "FormattedExport.xlsx")

    workbook.SaveAs(outputPath)
    MessageBox.Show("Formatted export complete.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
$vbLabelText   $csharpLabel

C# DataGridView導出到Excel並格式化:完整指南:圖片4 - 生成的格式化Excel文件的輸出

格式化程式碼採用了多種技術。 標題行有一個藍色背景(#4472C4),白色文字、12點粗體字和居中對齊——這是標準的商務表格樣式。 資料行交替在每個偶數行的白色和淺灰色(#D6DCE5)間切換,這讓使用者在寬表中閱讀時不會丟失位置。 價格列使用Excel內建的貨幣格式($#,##0.00),因此在不改變底層資料的情況下,以美元符號和兩位小數點在電子表格中顯示。 AutoSizeColumn使每列符合其最長值,因此不會截斷內容。

您可以進一步擴展此模式,新增單元格邊框樣式條件格式化資料驗證規則。 對於必須符合公司範本的報告,您還可以設置頁面佈局和列印區域,使得導出的檔案在不需要調整的情況下立即進行列印。

如何處理大型資料集和性能調優?

DataGridView被綁定到數千行時,逐個單元迭代會顯著緩慢。 兩個優化顯著提高性能。 首先,使用SetCellValue調用。 其次,如果您的資料源是一個DataGridView行提取值:

void ExportLargeDataset(DataTable sourceTable)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.DefaultWorkSheet;

    // Direct DataTable load -- fastest path for large data
    worksheet.LoadFromDataTable(sourceTable, true);

    // Apply header styling after load
    int colCount = sourceTable.Columns.Count;
    for (int col = 0; col < colCount; col++)
    {
        char colLetter = (char)('A' + col);
        worksheet[$"{colLetter}1"].Style.Font.Bold = true;
        worksheet[$"{colLetter}1"].Style.SetBackgroundColor("#4472C4");
        worksheet[$"{colLetter}1"].Style.Font.Color = "#FFFFFF";
    }

    workbook.SaveAs(Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "LargeExport.xlsx"
    ));
}
void ExportLargeDataset(DataTable sourceTable)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.DefaultWorkSheet;

    // Direct DataTable load -- fastest path for large data
    worksheet.LoadFromDataTable(sourceTable, true);

    // Apply header styling after load
    int colCount = sourceTable.Columns.Count;
    for (int col = 0; col < colCount; col++)
    {
        char colLetter = (char)('A' + col);
        worksheet[$"{colLetter}1"].Style.Font.Bold = true;
        worksheet[$"{colLetter}1"].Style.SetBackgroundColor("#4472C4");
        worksheet[$"{colLetter}1"].Style.Font.Color = "#FFFFFF";
    }

    workbook.SaveAs(Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "LargeExport.xlsx"
    ));
}
Option Strict On



Sub ExportLargeDataset(sourceTable As DataTable)
    Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
    Dim worksheet As WorkSheet = workbook.DefaultWorkSheet

    ' Direct DataTable load -- fastest path for large data
    worksheet.LoadFromDataTable(sourceTable, True)

    ' Apply header styling after load
    Dim colCount As Integer = sourceTable.Columns.Count
    For col As Integer = 0 To colCount - 1
        Dim colLetter As Char = ChrW(AscW("A"c) + col)
        worksheet($"{colLetter}1").Style.Font.Bold = True
        worksheet($"{colLetter}1").Style.SetBackgroundColor("#4472C4")
        worksheet($"{colLetter}1").Style.Font.Color = "#FFFFFF"
    Next

    workbook.SaveAs(Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
        "LargeExport.xlsx"
    ))
End Sub
$vbLabelText   $csharpLabel

對於超過10,000行的資料集,在背景執行緒上運行導出保持UI響應。把導出邏輯包裹在MessageBox.Show調用回UI執行緒。 IronXL是執行緒安全的,具有對單獨WorkBook實例的寫操作,所以如果需要,您可以同時運行多次導出。

更多性能資源:

如何將IronXL與Microsoft互操作進行DataGridView導出的比較?

許多開發者起初使用Microsoft Excel互操作,因為它與Office一起提供,而且不需要額外的包。 然而,互操作在生產環境中迅速顯示出來的現實成本。 下表總結了關鍵差異:

IronXL與Microsoft Excel互操作的DataGridView導出對比
功能 IronXL Microsoft互操作
需要安裝Microsoft Excel
可在伺服器/雲環境中運行 否(Microsoft不支持)
需要清理COM物件 是(Marshal.ReleaseComObject)
處理大型資料集的性能 快(純.NET) 慢(COM組件編輯開銷)
安裝方法 NuGet COM引用/Office安裝
支持的.NET版本 .NET 4.6.2 -- .NET 10 .NET Framework僅限(有限)
XLSX、CSV、ODS支持 僅通過Excel支持XLSX/XLS

Microsoft自己的文件警告不宜在伺服器或服務帳戶上使用Office互操作,並指出穩定性和授權問題。 IronXL在Azure App Service、Windows Service主機、Docker容器以及其他任何運行桌面應用程式如Excel不切實際的無頭環境中工作正常。

對於已使用互操作並希望遷移的團隊,IronXL的API足夠緊密地映射,大多數WorkSheet操作可以直接轉換。 IronXL遷移指南涵蓋了常見的互操作模式及其IronXL等效項。

您接下來的步驟是什麼?

使用IronXL將DataGridView資料導出到Excel只需要一個NuGet包安裝和幾行程式碼,取代了脆弱的COM互操作方法,成為一個乾淨、可維護的解決方案,適用於任何部署環境。 此處涵蓋的技術——基本導出、格式化輸出、大資料集優化和比較表——為您提供了在生產Windows窗體應用程式中推出此功能所需的一切。

從這裡開始,探索這些相關功能:

開始免費的IronXL試用以在項目中測試完整功能集,或在準備好用於生產部署時查看IronXL授權選項

常見問題

如何在 C# 中將 DataGridView 資料匯出到 Excel?

透過 NuGet 安裝 IronXL,從您的 DataGridView 中提取 DataTable,建立 WorkBook 和 WorkSheet,呼叫 worksheet.LoadFromDataTable(dt, true),然後使用 workbook.SaveAs 儲存。

匯出 DataGridView 至 Excel 時有哪些格式化選項?

IronXL 支援粗體字、背景顏色、字體顏色、水平對齊、數字格式(如貨幣)、自動調整欄寬、邊框樣式和條件格式化。

匯出 DataGridView 資料是否需要安裝 Microsoft Excel?

不需要。IronXL 是純 .NET 程式庫,生成 Excel 檔案無需 Microsoft Office 或任何機器上的 COM 註冊。

匯出 DataGridView 至 Excel 時可以設計標題嗎?

可以。在寫入標題行後,透過地址存取每個標題單元格,並設置 Style.Font.Bold、Style.SetBackgroundColor 和 Style.Font.Color 屬性。

匯出 DataGridView 至 Excel 時如何應用交替行顏色?

跟蹤遍歷 DataGridView 行的行索引,對偶數行應用範圍樣式,使用 worksheet[rangeAddress].Style.SetBackgroundColor 搭配您選擇的十六進位顏色。

匯出 DataGridView 至 Excel 時如何處理大型資料集?

直接將底層 DataTable 傳遞給 worksheet.LoadFromDataTable,而不是一個一個單元格迭代。對於非常大的資料集,使用 Task.Run 在後台執行匯出。

IronXL 與 Microsoft Excel Interop 比較 DataGridView 匯出時有何不同?

IronXL 不需要 Microsoft Excel,可在伺服器和雲端環境中運作,無需 COM 清理程式碼,且在大型資料集下效能顯著較快。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話