如何在 C# 中將 GridView 匯出到 Excel 並保留格式
在將 GridView 資料匯出至 Excel 時,同時保留顏色、字型、交錯的行背景色及邊框,是幾乎所有以資料為導向的 ASP.NET 或 Windows Forms 應用程式中都會出現的需求。 傳統方法—使用 HtmlTextWriter 和 StringWriter 將控制項渲染為 HTML—生成的檔案在 Excel 中帶有格式警告,並且對使用者來說毫無反應。 IronXL 透過完全以 C# 生成原生 XLSX 檔案來解決此問題,無需依賴 Microsoft Office,讓您能精確控制每個儲存格的樣式。
如何在 .NET 專案中安裝程式庫?
在編寫任何匯出程式碼之前,請先從 NuGet 安裝 IronXL。 開啟軟體包管理器控制台並執行:
Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
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
無需額外的執行階段元件或 Office 互通功能。 此函式庫會寫入原生 XLSX 二進位檔案,可在 Microsoft Excel、LibreOffice Calc 及 Google 試算表中完美開啟。
如何將 Windows Forms 的 DataGridView 連同儲存格格式一併匯出至 Excel?
Windows Forms 應用程式使用 DataGridView 控件,而不是基於 Web 的 GridView 控件。 兩種情況的匯出模式相同:從行和儲存格中提取值,建立 IronXL 工作簿,套用樣式,然後儲存或串流結果。
最可靠的方法是將控制項的 DataSource 屬性強制轉換為 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
WorkBook.Create 初始化一個新的記憶體中的 XLSX 格式工作簿。 DefaultWorkSheet 傳回第一個工作表,您可以在儲存之前透過其 Name 屬性重命名該工作表。 SetCellValue 接受字串、整數、雙精確度浮點數和 DateTime 值 -- IronXL 會自動選擇正確的儲存格類型。
交替行顏色模式 -- row % 2 == 0 選擇 #D6DCE5,否則選擇 #FFFFFF -- 反映了 Excel 內建的帶狀行表格樣式。 您可以替換為任何符合您應用程式設計系統的六位元組十六進位顏色代碼。
輸出影像
使用 IronXL 將 GridView 匯出到 Excel 並設定格式(C#):圖 1 - GridView 輸出
如何將 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()
Response.AddHeader 與 content-disposition: attachment 會強制所有現代瀏覽器彈出檔案下載對話方塊。 MIME 類型 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 是 XLSX 檔案的註冊類型,可防止瀏覽器嘗試以內聯方式顯示二進位內容。
對於 ASP.NET Core 應用程序,在控制器操作中將 Response.BinaryWrite 替換為 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
此模式具有可組合性——您可以根據報表需求添加任意數量的條件檢查。 由於 IronXL 是以單元格為單位運作的,您可以透過在基礎行樣式之後套用條件樣式,將條件格式化與交替行色彩邏輯結合使用。
如何設定欄位寬度並固定標題列?
Professional 格式化的 Excel 匯出檔應包含適當的欄位寬度,並設定固定標題列,以便使用者在瀏覽大型資料集時,欄位名稱仍能清晰可見。
IronXL 透過 WorkSheet 列存取器公開列寬,並透過 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)
若用於正式環境,建議根據各欄位的最大字元數來計算寬度,而非使用固定值。 遍歷 DataTable 列的值,測量字串長度,並乘以適合所選字體大小的字元寬度因子。
您亦可透過 C# 獨立於行帶狀樣式邏輯之外,為 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
此方法傳回一個 byte[],您可以將其寫入磁碟、從 API 端點串流傳輸、附加到電子郵件或快取到記憶體中。 有關相關技術,請參閱《將 DataTable 匯出至 Excel 的指南》以及《將 DataTable 匯出至 Excel 的最快方法》教學。
您如何處理大型資料集與效能問題?
將數萬行資料匯出至 Excel 時,必須注意記憶體分配。 針對大型網格中的每個儲存格建立新的儲存格樣式物件,是最常見的效能瓶頸。 請盡可能重複使用樣式定義,透過在範圍物件上設定樣式,而非個別儲存格:
| 資料集大小 | 建議的翻譯方法 | 關鍵考慮因素 |
|---|---|---|
| 最多 5,000 行 | 逐個儲存格樣式設定迴圈 | 簡潔的程式碼,微乎其微的開銷 |
| 5,000 -- 50,000 行 | 範圍層級的風格應用 | 顯著減少物件分配 |
| 50,000+ 行 | DataTable 直接匯出,最小化樣式 | 盡量減少單元格操作;若可行,請使用串流處理 |
對於分頁 GridView,請務必設定 AllowPaging = false 並在匯出之前重新綁定。 分頁功能會限制控制項中可見的列數,因此分頁匯出僅會擷取當前頁面而非整個資料集——這正是導致匯出不完整錯誤的常見原因。
您也可以查看在 C# 中將物件清單匯出到 Excel 的指南,以了解適用於強類型集合而不是非類型行的模式。
如何在 ASP.NET Core 或 Blazor 中匯出 GridView?
ASP.NET Core 和 Blazor 應用程式沒有 Web Forms 控件,但底層資料匯出挑戰是相同的:取得物件集合或數據,建立樣式化的工作簿,並交付檔案。工作簿建立代碼完全相同; 僅傳遞機制有所變更。
在 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
Blazor 下載模式的完整操作指南請參閱《Blazor 匯出至 Excel 教學》。 若需了解 ASP.NET Core 控制器的方法,請參閱 ASP.NET Core 匯出 Excel 教學。
字型樣式與邊框選項
IronXL 透過每個儲存格上的 Style 物件公開細粒度的字體和邊框控制。 C# 中 Excel 字型樣式的完整範圍包含粗體、斜體、底線、字號及顏色。 透過 BorderType 提供的邊框類型包括細邊框、中等邊框、粗邊框、虛線邊框、點線邊框、雙線邊框和幾種細線變體。
針對合併的標題列或摘要頁尾,IronXL 亦支援透過 C# 在 Excel 中合併儲存格——當您希望在資料表上方設置一個橫跨多欄的標題儲存格時,此功能便十分實用。
若要在填入資料後自動調整欄位寬度,請參閱《使用 C# 在 Excel 中自動調整儲存格》指南,了解建議的做法。
為何原生 Excel 函式庫產出的匯出檔比 HtmlTextWriter 更為整潔?
傳統的 ASP.NET 匯出技術—重寫 VerifyRenderingInServerForm,建立 StringWriter 和 HtmlTextWriter,並將呈現的控制項寫入回應—產生副檔名為 .xls 的控制項寫入檔案。 Microsoft Excel 開啟此類檔案時會顯示相容性警告,因為該檔案實際上並非以 Excel 二進位或 OOXML 格式儲存。 樣式僅限於 Excel 能部分解析的內嵌 CSS。 無法使用條件格式化。 在非 Windows 平台或使用 LibreOffice 的使用者,將看到品質較差的輸出結果。
IronXL 可直接寫入 Open XML 試算表格式 (OOXML)。 結果是一個正確的 .xlsx 檔案——與 Excel 本身創建的檔案完全相同——在 macOS 上的 Excel、LibreOffice、Google Sheets 和 Numbers 中開啟時不會出現警告。 格式設定採用試算表樣式而非 HTML 屬性,因此能確保在往返傳輸及跨平台檢視時仍能完整保留。
| 方法 | 檔案格式 | 格式警告 | 完整風格支援 | 辦公室要求 |
|---|---|---|---|---|
| HtmlTextWriter + StringWriter | 偽裝成 XLS 的 HTML | 是 | 無 | 無 |
| Office 互通 (COM) | 原生 XLS/XLSX | 無 | 是 | 是 |
| IronXL | 原生 XLSX/XLS | 無 | 是 | 無 |
微軟關於 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 等交付模型。
更進一步:
- 立即開始 IronXL 的免費試用,使用您的自有資料測試完整的格式設定與匯出功能。
- 請參閱 IronXL 文件以獲取完整的 API 參考,內容涵蓋樞紐分析表、圖表及資料驗證。
- 探索如何使用 C# 建立 Excel 報表,將上述匯出模式與計算出的摘要及圖表結合。
- 若您的應用程式亦需處理上傳的試算表,請參閱《使用 C# 讀取 Excel 檔案》以了解相應的匯入工作流程。
- 若需除 XLSX 以外的 CSV 格式匯出,請參閱 C# 匯出至 CSV 教學指南。
- 若您要從 DataGridView 匯出資料,且需將欄位標題作為第一行,請參閱專門的《DataGridView 匯出至 Excel 並包含欄位標題》指南。
常見問題解答
如何在 C# 中將 GridView 資料匯出至 Excel?
您可透過 IronXL程式庫,在 C# 中將 GridView 資料匯出至 Excel。此程式庫讓您能輕鬆地以程式化方式建立 Excel 檔案並匯出資料,包含格式與樣式。
為什麼應該使用 IronXL 來匯出 GridView 資料?
IronXL 透過直觀的 API 簡化了 GridView 資料匯出的流程,讓您能輕鬆維持格式並套用樣式,這在傳統方法中往往相當困難。
IronXL 在將 GridView 匯出至 Excel 時是否支援格式設定?
是的,IronXL 支援多種格式設定選項,包括字型、顏色和儲存格樣式,確保您匯出的 Excel 檔案看起來 Professional 且能維持預期的設計。
我可以自訂由 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 時,能設定依據儲存格值動態調整的規則與樣式。


