跳至頁尾內容
USING IRONXL

如何在 C# 中將 GridView 匯出到 Excel 並保留格式

將GridView資料匯出到Excel時,保存顏色、字型、交替行背景和邊框是幾乎每個以資料為驅動的ASP.NET或Windows Forms應用程式中的一個需求。 傳統的方法——使用StringWriter將控制項呈現為HTML——會生成在Excel中帶有格式警告的檔案,並且對於使用者來說會無聲失敗。 IronXL透過完全在C#中生成原生XLSX檔案來解決這個問題,無需依賴Microsoft Office,您可以精確控制每個儲存格的樣式。

如何在.NET專案中安裝程式庫?

在編寫任何匯出程式碼之前,從NuGet安裝IronXL。 打開套件管理控制台並執行以下指令:

Install-Package IronXL.Excel

IronXL支援.NET 8、.NET 9和.NET 10,以及.NET Framework 4.6.2及更高版本。 安裝後,將以下using指令新增到任何需要執行Excel操作的檔案中:

using IronXL;
using IronXL.Styles;
using IronXL;
using IronXL.Styles;
Imports IronXL
Imports IronXL.Styles
$vbLabelText   $csharpLabel

不需要額外的執行時或Office互操作。 該程式庫撰寫原生XLSX二進位檔案,可在Microsoft Excel、LibreOffice Calc和Google Sheets中清晰開啟。

如何在具有儲存格格式的情況下將Windows Forms的DataGridView匯出到Excel?

Windows Forms應用程式使用DataGridView控制項,而非以網頁為基礎的GridView。 在兩種情況下,匯出模式都是相同的:從行和儲存格中提取值,建立IronXL活頁簿,應用樣式,然後保存或串流結果。

最可靠的方法是將控制項的DataTable以避免迭代可能被過濾或分頁的視覺行:

using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

DataTable dt = (DataTable)dataGridView1.DataSource;

WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.DefaultWorkSheet;

// Header row -- bold, blue background, white text
for (int col = 0; col < dt.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
    var cell = sheet.GetCellAt(0, col);
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#4472C4");
    cell.Style.Font.Color = "#FFFFFF";
    cell.Style.BottomBorder.Type = BorderType.Thin;
}

// Data rows -- alternating row color
for (int row = 0; row < dt.Rows.Count; row++)
{
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        string value = dt.Rows[row][col]?.ToString() ?? string.Empty;
        sheet.SetCellValue(row + 1, col, value);

        var cell = sheet.GetCellAt(row + 1, col);
        cell.Style.SetBackgroundColor(row % 2 == 0 ? "#D6DCE5" : "#FFFFFF");
        cell.Style.BottomBorder.Type = BorderType.Thin;
    }
}

// Save via dialog
using var saveDialog = new SaveFileDialog
{
    Filter = "Excel Files|*.xlsx",
    FileName = "GridViewExport.xlsx"
};

if (saveDialog.ShowDialog() == DialogResult.OK)
{
    workBook.SaveAs(saveDialog.FileName);
    MessageBox.Show("Export successful.", "Export",
        MessageBoxButtons.OK, MessageBoxIcon.Information);
}
using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

DataTable dt = (DataTable)dataGridView1.DataSource;

WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.DefaultWorkSheet;

// Header row -- bold, blue background, white text
for (int col = 0; col < dt.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
    var cell = sheet.GetCellAt(0, col);
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#4472C4");
    cell.Style.Font.Color = "#FFFFFF";
    cell.Style.BottomBorder.Type = BorderType.Thin;
}

// Data rows -- alternating row color
for (int row = 0; row < dt.Rows.Count; row++)
{
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        string value = dt.Rows[row][col]?.ToString() ?? string.Empty;
        sheet.SetCellValue(row + 1, col, value);

        var cell = sheet.GetCellAt(row + 1, col);
        cell.Style.SetBackgroundColor(row % 2 == 0 ? "#D6DCE5" : "#FFFFFF");
        cell.Style.BottomBorder.Type = BorderType.Thin;
    }
}

// Save via dialog
using var saveDialog = new SaveFileDialog
{
    Filter = "Excel Files|*.xlsx",
    FileName = "GridViewExport.xlsx"
};

if (saveDialog.ShowDialog() == DialogResult.OK)
{
    workBook.SaveAs(saveDialog.FileName);
    MessageBox.Show("Export successful.", "Export",
        MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Imports IronXL
Imports IronXL.Styles
Imports System
Imports System.Data
Imports System.IO
Imports System.Windows.Forms

Dim dt As DataTable = DirectCast(dataGridView1.DataSource, DataTable)

Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workBook.DefaultWorkSheet

' Header row -- bold, blue background, white text
For col As Integer = 0 To dt.Columns.Count - 1
    sheet.SetCellValue(0, col, dt.Columns(col).ColumnName)
    Dim cell = sheet.GetCellAt(0, col)
    cell.Style.Font.Bold = True
    cell.Style.SetBackgroundColor("#4472C4")
    cell.Style.Font.Color = "#FFFFFF"
    cell.Style.BottomBorder.Type = BorderType.Thin
Next

' Data rows -- alternating row color
For row As Integer = 0 To dt.Rows.Count - 1
    For col As Integer = 0 To dt.Columns.Count - 1
        Dim value As String = If(dt.Rows(row)(col)?.ToString(), String.Empty)
        sheet.SetCellValue(row + 1, col, value)

        Dim cell = sheet.GetCellAt(row + 1, col)
        cell.Style.SetBackgroundColor(If(row Mod 2 = 0, "#D6DCE5", "#FFFFFF"))
        cell.Style.BottomBorder.Type = BorderType.Thin
    Next
Next

' Save via dialog
Using saveDialog As New SaveFileDialog With {
    .Filter = "Excel Files|*.xlsx",
    .FileName = "GridViewExport.xlsx"
}
    If saveDialog.ShowDialog() = DialogResult.OK Then
        workBook.SaveAs(saveDialog.FileName)
        MessageBox.Show("Export successful.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End If
End Using
$vbLabelText   $csharpLabel

WorkBook.Create以XLSX格式初始化一個新的記憶體活頁簿。 Name屬性在保存之前重新命名。 DateTime值——IronXL會自動選擇正確的儲存格型別。

交替行顏色模式——#FFFFFF——與Excel內建的帶狀行表格樣式相呼應。 您可以替換任何符合應用程式設計系統的六字元十六進位顏色。

輸出圖像

使用IronXL將GridView匯出到具有格式的Excel:圖像 1 - GridView輸出

使用IronXL將GridView匯出到具有格式的Excel:圖像 2 - Excel輸出

使用IronXL將GridView匯出到具有格式的Excel:圖像 3 - 訊息輸出

如何將ASP.NET的GridView匯出到Excel並將檔案串流到瀏覽器中?

Web應用程式需要不同的交付機制。 而不是寫入到檔案系統中,您需要將活頁簿序列化為MemoryStream並透過正確的標頭將其寫入HTTP回應,使瀏覽器將其視為檔案下載。

對分頁GridView的重要預備步驟:禁用分頁(AllowPaging = false)並在匯出之前重新綁定資料來源,這樣每個記錄——不僅是當前頁——都被捕捉到。

using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;
using System.Web.UI;

// Disable paging so all rows are captured
GridView1.AllowPaging = false;
GridView1.DataBind();

DataTable dt = (DataTable)GridView1.DataSource;

WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.DefaultWorkSheet;

// Header row
for (int col = 0; col < dt.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
    var cell = sheet.GetCellAt(0, col);
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#2E75B6");
    cell.Style.Font.Color = "#FFFFFF";
    cell.Style.HorizontalAlignment = HorizontalAlignment.Center;
    cell.Style.BottomBorder.Type = BorderType.Medium;
}

// Data rows
for (int row = 0; row < dt.Rows.Count; row++)
{
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        var cell = sheet.GetCellAt(row + 1, col);
        cell.Style.SetBackgroundColor(row % 2 == 0 ? "#DEEAF1" : "#FFFFFF");
        cell.Style.BottomBorder.Type = BorderType.Thin;
        cell.Style.LeftBorder.Type = BorderType.Thin;
        cell.Style.RightBorder.Type = BorderType.Thin;
    }
}

// Stream to browser
byte[] fileBytes = workBook.ToByteArray();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=GridViewExport.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;
using System.Web.UI;

// Disable paging so all rows are captured
GridView1.AllowPaging = false;
GridView1.DataBind();

DataTable dt = (DataTable)GridView1.DataSource;

WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.DefaultWorkSheet;

// Header row
for (int col = 0; col < dt.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
    var cell = sheet.GetCellAt(0, col);
    cell.Style.Font.Bold = true;
    cell.Style.SetBackgroundColor("#2E75B6");
    cell.Style.Font.Color = "#FFFFFF";
    cell.Style.HorizontalAlignment = HorizontalAlignment.Center;
    cell.Style.BottomBorder.Type = BorderType.Medium;
}

// Data rows
for (int row = 0; row < dt.Rows.Count; row++)
{
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        var cell = sheet.GetCellAt(row + 1, col);
        cell.Style.SetBackgroundColor(row % 2 == 0 ? "#DEEAF1" : "#FFFFFF");
        cell.Style.BottomBorder.Type = BorderType.Thin;
        cell.Style.LeftBorder.Type = BorderType.Thin;
        cell.Style.RightBorder.Type = BorderType.Thin;
    }
}

// Stream to browser
byte[] fileBytes = workBook.ToByteArray();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=GridViewExport.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
Imports IronXL
Imports IronXL.Styles
Imports System
Imports System.Data
Imports System.IO
Imports System.Web.UI

' Disable paging so all rows are captured
GridView1.AllowPaging = False
GridView1.DataBind()

Dim dt As DataTable = CType(GridView1.DataSource, DataTable)

Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workBook.DefaultWorkSheet

' Header row
For col As Integer = 0 To dt.Columns.Count - 1
    sheet.SetCellValue(0, col, dt.Columns(col).ColumnName)
    Dim cell = sheet.GetCellAt(0, col)
    cell.Style.Font.Bold = True
    cell.Style.SetBackgroundColor("#2E75B6")
    cell.Style.Font.Color = "#FFFFFF"
    cell.Style.HorizontalAlignment = HorizontalAlignment.Center
    cell.Style.BottomBorder.Type = BorderType.Medium
Next

' Data rows
For row As Integer = 0 To dt.Rows.Count - 1
    For col As Integer = 0 To dt.Columns.Count - 1
        sheet.SetCellValue(row + 1, col, If(dt.Rows(row)(col)?.ToString(), String.Empty))
        Dim cell = sheet.GetCellAt(row + 1, col)
        cell.Style.SetBackgroundColor(If(row Mod 2 = 0, "#DEEAF1", "#FFFFFF"))
        cell.Style.BottomBorder.Type = BorderType.Thin
        cell.Style.LeftBorder.Type = BorderType.Thin
        cell.Style.RightBorder.Type = BorderType.Thin
    Next
Next

' Stream to browser
Dim fileBytes As Byte() = workBook.ToByteArray()
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=GridViewExport.xlsx")
Response.BinaryWrite(fileBytes)
Response.End()
$vbLabelText   $csharpLabel

content-disposition: attachment在所有現代瀏覽器中強制進行檔案下載對話框。 MIME型別application/vnd.openxmlformats-officedocument.spreadsheetml.sheet是XLSX檔案的註冊型別,防止瀏覽器嘗試內聯顯示二進位內容。

對於ASP.NET Core應用程式,請在控制器操作中將File(fileBytes, contentType, fileName)——活頁簿建立邏輯相同。

如何根據儲存格值應用條件格式?

條件格式將符合特定標準的儲存格突出顯示——例如,用紅色標記過期日期或用橙色標記低於閾值的值。 IronXL在活頁簿構建的過程中在儲存格層級應用條件格式:

// Assume "DueDate" is column index 3 and "Amount" is column index 4
DateTime today = DateTime.Today;

for (int row = 0; row < dt.Rows.Count; row++)
{
    // Highlight past-due dates
    if (dt.Columns.Contains("DueDate") && dt.Rows[row]["DueDate"] != DBNull.Value)
    {
        DateTime dueDate = Convert.ToDateTime(dt.Rows[row]["DueDate"]);
        var dueDateCell = sheet.GetCellAt(row + 1, 3);
        if (dueDate < today)
        {
            dueDateCell.Style.SetBackgroundColor("#FF0000");
            dueDateCell.Style.Font.Color = "#FFFFFF";
            dueDateCell.Style.Font.Bold = true;
        }
    }

    // Highlight amounts below threshold
    if (dt.Columns.Contains("Amount") && dt.Rows[row]["Amount"] != DBNull.Value)
    {
        decimal amount = Convert.ToDecimal(dt.Rows[row]["Amount"]);
        var amountCell = sheet.GetCellAt(row + 1, 4);
        if (amount < 100m)
        {
            amountCell.Style.SetBackgroundColor("#FFC000");
        }
    }
}
// Assume "DueDate" is column index 3 and "Amount" is column index 4
DateTime today = DateTime.Today;

for (int row = 0; row < dt.Rows.Count; row++)
{
    // Highlight past-due dates
    if (dt.Columns.Contains("DueDate") && dt.Rows[row]["DueDate"] != DBNull.Value)
    {
        DateTime dueDate = Convert.ToDateTime(dt.Rows[row]["DueDate"]);
        var dueDateCell = sheet.GetCellAt(row + 1, 3);
        if (dueDate < today)
        {
            dueDateCell.Style.SetBackgroundColor("#FF0000");
            dueDateCell.Style.Font.Color = "#FFFFFF";
            dueDateCell.Style.Font.Bold = true;
        }
    }

    // Highlight amounts below threshold
    if (dt.Columns.Contains("Amount") && dt.Rows[row]["Amount"] != DBNull.Value)
    {
        decimal amount = Convert.ToDecimal(dt.Rows[row]["Amount"]);
        var amountCell = sheet.GetCellAt(row + 1, 4);
        if (amount < 100m)
        {
            amountCell.Style.SetBackgroundColor("#FFC000");
        }
    }
}
Imports System

' Assume "DueDate" is column index 3 and "Amount" is column index 4
Dim today As DateTime = DateTime.Today

For row As Integer = 0 To dt.Rows.Count - 1
    ' Highlight past-due dates
    If dt.Columns.Contains("DueDate") AndAlso dt.Rows(row)("DueDate") IsNot DBNull.Value Then
        Dim dueDate As DateTime = Convert.ToDateTime(dt.Rows(row)("DueDate"))
        Dim dueDateCell = sheet.GetCellAt(row + 1, 3)
        If dueDate < today Then
            dueDateCell.Style.SetBackgroundColor("#FF0000")
            dueDateCell.Style.Font.Color = "#FFFFFF"
            dueDateCell.Style.Font.Bold = True
        End If
    End If

    ' Highlight amounts below threshold
    If dt.Columns.Contains("Amount") AndAlso dt.Rows(row)("Amount") IsNot DBNull.Value Then
        Dim amount As Decimal = Convert.ToDecimal(dt.Rows(row)("Amount"))
        Dim amountCell = sheet.GetCellAt(row + 1, 4)
        If amount < 100D Then
            amountCell.Style.SetBackgroundColor("#FFC000")
        End If
    End If
Next row
$vbLabelText   $csharpLabel

此模式是可組合的——根據您的報告需求新增盡可能多的條件檢查。 由於IronXL以逐儲存格的基準運作,您可以在應用基礎行樣式後混合使用交替行顏色邏輯的條件格式。

如何設置欄寬和凍結標題行?

一個專業格式的Excel匯出包括適當的欄寬和凍結的標題行,使得當使用者滾動瀏覽大量資料集時,欄名稱保持可見。

IronXL透過FreezeRows方法凍結標題。

// Auto-size columns 0 through the last column index
for (int col = 0; col < dt.Columns.Count; col++)
{
    // Set column width in character units (1 unit ≈ one default character width)
    sheet.SetColumnWidth(col, 20);
}

// Freeze the first row (index 0) so the header stays visible while scrolling
sheet.FreezeRows(1);

// Optionally set row height for the header (in points)
sheet.SetRowHeight(0, 20);
// Auto-size columns 0 through the last column index
for (int col = 0; col < dt.Columns.Count; col++)
{
    // Set column width in character units (1 unit ≈ one default character width)
    sheet.SetColumnWidth(col, 20);
}

// Freeze the first row (index 0) so the header stays visible while scrolling
sheet.FreezeRows(1);

// Optionally set row height for the header (in points)
sheet.SetRowHeight(0, 20);
' Auto-size columns 0 through the last column index
For col As Integer = 0 To dt.Columns.Count - 1
    ' Set column width in character units (1 unit ≈ one default character width)
    sheet.SetColumnWidth(col, 20)
Next

' Freeze the first row (index 0) so the header stays visible while scrolling
sheet.FreezeRows(1)

' Optionally set row height for the header (in points)
sheet.SetRowHeight(0, 20)
$vbLabelText   $csharpLabel

在生產環境中,建議基於每個欄的最大字元數計算寬度,而不是使用固定值。 迭代DataTable欄值,測量字串長度,並乘以與所選字型大小相符的字寬因子。

您還可以單獨應用背景色到Excel儲存格中,不受行帶狀邏輯的影響,以獲得更細緻的樣式方法。

如何在不使用GridView控制項的情況下將DataTable匯出到Excel?

許多.NET應用程式透過服務呼叫或資料庫查詢填充資料,並將其保存在DataTable中,而不需要將其綁定到UI控制項上。 您可以直接將DataTable匯出到Excel,不需要實例化GridView。

對於需要在伺服器上生成Excel檔案的後台任務、計畫報告和API端點,這是最有效的路徑:

using IronXL;
using IronXL.Styles;
using System.Data;

public static byte[] DataTableToExcelBytes(DataTable dt, string sheetName = "Report")
{
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workBook.CreateWorkSheet(sheetName);

    // Header
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = sheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
    }

    // Data
    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        }
    }

    return workBook.ToByteArray();
}
using IronXL;
using IronXL.Styles;
using System.Data;

public static byte[] DataTableToExcelBytes(DataTable dt, string sheetName = "Report")
{
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workBook.CreateWorkSheet(sheetName);

    // Header
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = sheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
    }

    // Data
    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        }
    }

    return workBook.ToByteArray();
}
Imports IronXL
Imports IronXL.Styles
Imports System.Data

Public Shared Function DataTableToExcelBytes(dt As DataTable, Optional sheetName As String = "Report") As Byte()
    Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
    Dim sheet As WorkSheet = workBook.CreateWorkSheet(sheetName)

    ' Header
    For col As Integer = 0 To dt.Columns.Count - 1
        sheet.SetCellValue(0, col, dt.Columns(col).ColumnName)
        Dim cell = sheet.GetCellAt(0, col)
        cell.Style.Font.Bold = True
        cell.Style.SetBackgroundColor("#4472C4")
        cell.Style.Font.Color = "#FFFFFF"
    Next

    ' Data
    For row As Integer = 0 To dt.Rows.Count - 1
        For col As Integer = 0 To dt.Columns.Count - 1
            sheet.SetCellValue(row + 1, col, If(dt.Rows(row)(col)?.ToString(), String.Empty))
        Next
    Next

    Return workBook.ToByteArray()
End Function
$vbLabelText   $csharpLabel

此方法返回可以寫入磁碟、從API端點串流、附加到電子郵件或快取在記憶體中的byte[]。 有關相關技術,請參考將DataTable匯出到Excel的指南和從最快將DataTable匯出到Excel的教程

如何處理大型資料集和效能?

將數萬行匯出到Excel需要注意記憶體分配。 為大型網格中的每個儲存格建立一個新的儲存格樣式物件是最常見的效能瓶頸。 儘可能重用樣式定義,透過在範圍物件上設置樣式而不是個別儲存格:

IronXL根據資料集大小的匯出方法
資料集大小 建議的方法 關鍵考量
最多5,000行 逐儲存格樣式迴圈 簡單的程式碼,幾乎可以忽略的開銷
5,000至50,000行 範圍級別樣式應用 顯著減少物件分配
超過50,000行 DataTable直接匯出,最小樣式 最小化逐儲存格的操作;如果可用,請使用串流

對於分頁的GridView,請始終設置AllowPaging = false並在匯出前重新綁定。 分頁限制了控制項中可見的行數,因此分頁的匯出僅捕捉當前頁面而不是整個資料集——這是未完成的匯出錯誤的常見來源。

您還可以查看將物件列表匯出到Excel的指南,以獲得與強型別集合而不是無型別的DataTable行一起工作的一些模式。

如何在ASP.NET Core或Blazor中匯出GridView?

ASP.NET Core和Blazor應用程式沒有Web Forms DataTable,構建樣式化的活頁簿,並交付檔案。工作簿建立程式碼是相同的; 只有交付機制有所變化。

在Blazor應用程式中,透過JavaScript互操作來觸發檔案下載:

// In a Blazor component or service
using IronXL;
using System.Data;
using Microsoft.JSInterop;

public async Task ExportToExcelAsync(DataTable dt, IJSRuntime js)
{
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workBook.DefaultWorkSheet;

    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = sheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
    }

    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        }
    }

    byte[] fileBytes = workBook.ToByteArray();
    string base64 = Convert.ToBase64String(fileBytes);
    await js.InvokeVoidAsync("downloadFileFromBase64", base64, "GridViewExport.xlsx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
// In a Blazor component or service
using IronXL;
using System.Data;
using Microsoft.JSInterop;

public async Task ExportToExcelAsync(DataTable dt, IJSRuntime js)
{
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workBook.DefaultWorkSheet;

    for (int col = 0; col < dt.Columns.Count; col++)
    {
        sheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = sheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
    }

    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            sheet.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);
        }
    }

    byte[] fileBytes = workBook.ToByteArray();
    string base64 = Convert.ToBase64String(fileBytes);
    await js.InvokeVoidAsync("downloadFileFromBase64", base64, "GridViewExport.xlsx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
Imports IronXL
Imports System.Data
Imports Microsoft.JSInterop

Public Async Function ExportToExcelAsync(dt As DataTable, js As IJSRuntime) As Task
    Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
    Dim sheet As WorkSheet = workBook.DefaultWorkSheet

    For col As Integer = 0 To dt.Columns.Count - 1
        sheet.SetCellValue(0, col, dt.Columns(col).ColumnName)
        Dim cell = sheet.GetCellAt(0, col)
        cell.Style.Font.Bold = True
        cell.Style.SetBackgroundColor("#4472C4")
        cell.Style.Font.Color = "#FFFFFF"
    Next

    For row As Integer = 0 To dt.Rows.Count - 1
        For col As Integer = 0 To dt.Columns.Count - 1
            sheet.SetCellValue(row + 1, col, If(dt.Rows(row)(col)?.ToString(), String.Empty))
        Next
    Next

    Dim fileBytes As Byte() = workBook.ToByteArray()
    Dim base64 As String = Convert.ToBase64String(fileBytes)
    Await js.InvokeVoidAsync("downloadFileFromBase64", base64, "GridViewExport.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
End Function
$vbLabelText   $csharpLabel

Blazor匯出到Excel教程中有完整的Blazor下載模式演練。 對於ASP.NET Core控制器的方法,請參見ASP.NET Core匯出Excel教程

字型樣式和邊框選項

IronXL透過Style物件提供每個儲存格的精細字型和邊框控制。 整個C#中的Excel字型樣式範圍包括粗體、斜體、下劃線、大小和顏色。 BorderType提供的邊框型別包括細、適中、粗、虛線、點線、雙線和多種細線變體。

對於合併的標題行或摘要頁腳,IronXL還支援使用C#合併Excel中的儲存格——當您希望在資料表上方有一個跨越多列的單一標題儲存格時很有用。

要在填充資料後自動調整欄寬,請參考C#中如何自動調整Excel儲存格的指南以獲得推薦的方法。

為什麼原生Excel程式庫會比HtmlTextWriter產生更乾淨的匯出?

傳統的ASP.NET匯出技術——覆寫.xls擴展名的HTML文件。 Microsoft Excel會以相容性警告打開這些檔案,因為文件實際上不是Excel二進位或OOXML格式。 樣式受到Excel部分解釋的內嵌CSS的限制。 條件格式是不可能的。 在非Windows平台或使用LibreOffice的使用者會看到品質下降的輸出。

IronXL直接撰寫開放XML電子表格格式(OOXML)。 結果是一個正確的.xlsx檔案——與Excel本身建立的文件相同——可在Excel、LibreOffice、Google Sheets和macOS上的Numbers中無警告地開啟。 格式以電子表格樣式而非HTML屬性進行編碼,因此可在往返和跨平台檢視中保留。

ASP.NET GridView匯出方法的比較
方法 文件格式 格式警告 完全的樣式支援 需要Office
HtmlTextWriter + StringWriter 偽裝成XLS的HTML
Office Interop (COM) 原生XLS/XLSX
IronXL 原生XLSX/XLS

Microsoft的Open XML SDK官方文件解釋了IronXL產生的基礎格式。 ECMA International維護的OOXML規範定義了可保證跨應用程式相容的標準。 Microsoft Docs上ASP.NET GridView控制項文件描述了匯出模式所讀取的控制模組。

您接下來的步驟是什麼?

您現在擁有使用IronXL將GridView和DataGridView資料匯出到正確格式化的XLSX檔的模式——涵蓋Windows Forms、ASP.NET Web Forms、ASP.NET Core和Blazor交付模式。

進一步研究:

常見問題

如何在C#中將GridView資料匯出至Excel?

您可以使用IronXL程式庫在C#中將GridView資料匯出至Excel。它允許您程式化地建立Excel文件並輕鬆匯出資料,包括格式和樣式。

為什麼要使用IronXL來匯出GridView資料?

IronXL通過其直觀的API簡化了GridView資料匯出的過程,使您能夠輕鬆保留格式並應用樣式,這在傳統方法中可能具有挑戰性。

IronXL是否支援在將GridView匯出至Excel時的格式化?

是的,IronXL支援各種格式選項,包括字體、顏色和單元格樣式,確保您的匯出Excel文件看起來專業且保留預期設計。

我可以自定義從GridView資料生成的Excel文件的外觀嗎?

IronXL提供了一系列自定義Excel文件的選項,允許您調整單元格樣式、字體、顏色等,以符合您的特定需求在匯出自GridView時。

使用IronXL是否可能將大型GridView資料集匯出至Excel?

IronXL能夠高效處理大型資料集,確保您可以將範圍龐大的GridView資料匯出至Excel而不會出現效能問題。

與其他方法相比,使用IronXL匯出GridView資料至Excel有哪些好處?

IronXL提供了一種更簡化和靈活的匯出GridView資料的方法,提供對格式化、自訂、處理大型資料集的強大支持,使其優於多種其他方法。

如何在匯出GridView至Excel時保持資料完整性?

IronXL透過在從GridView到Excel的匯出過程中準確轉換和保存資料型別和格式來確保資料完整性。

IronXL能否從具有複雜結構的GridView控制項匯出資料?

是的,IronXL可以有效處理並匯出具有複雜結構的GridView控制項的資料,在匯出的Excel文件中保持階層結構和格式。

IronXL可以將GridView資料匯出至哪些文件格式?

IronXL主要將資料匯出至如XLSX之類的Excel格式,但也支持其他格式如CSV,根據您的需要提供靈活性。

IronXL支援使用條件格式將GridView匯出嗎?

IronXL支持條件格式,允許您在將GridView資料匯出至Excel時設置規則和樣式,根據單元格值自動調整。

Curtis Chau
技術作家

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

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

Iron 支援團隊

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