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

將 DataGridView 資料匯出到 Excel 檔案是 Windows Forms 開發中最常見的任務之一。 在建置顯示表格資料的商業應用程式時——無論是銷售報告、庫存紀錄或客戶清單——使用者期望能點擊按鈕,即可獲得格式正確的 Excel 檔案,以便進行分享或進一步分析。 挑戰在於以簡潔的方式達成此目標,既不依賴每台終端使用者電腦都安裝 Microsoft Excel,也不必處理會導致記憶體洩漏或靜默崩潰的 COM 互通清理程式碼。 本指南將引導您完成使用IronXL將 DataGridView 匯出至 Excel 的 C# 完整流程,涵蓋從專案設定到進階儲存格格式設定的所有步驟,最終產生可用於生產環境的程式碼。
!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--
如何設定 Windows Forms 專案以進行 DataGridView 匯出?
匯出 DataGridView 資料的傳統方法依賴 Microsoft Interop—您需要開啟"新增參考",導航至 COM 選項卡,選擇 Microsoft Excel 物件庫,並編寫脆弱的程式碼來呼叫 Marshal.ReleaseComObject 以避免記憶體洩漏。 此模式要求在執行該應用程式的每台電腦上安裝 Microsoft Excel,處理大型資料集時效能緩慢,並且在缺少 Office 授權的部署環境中經常產生 COMException 錯誤。 微軟針對 Office 自動化所提供的官方指引中,明確建議在伺服器端及自動化情境下使用第三方函式庫。
IronXL 消除了所有這些依賴關係。 這是一個純 .NET 函式庫,無需 Microsoft Office 或任何 COM 註冊即可讀取和寫入 .xlsx、.xls、.csv 和 .ods 檔。 您可透過 NuGet 安裝,並立即開始編寫程式碼。
透過 NuGet 安裝 IronXL
首先在 Visual Studio 中建立一個以 .NET 10 為導向的新 Windows 窗體應用程式專案。在窗體表面新增一個 DataGridView 控制項和一個 Button 控制項。 將按鈕命名為 btnExport,並為其新增標籤"匯出至 Excel"。 接著開啟 NuGet 套件管理員主控台並執行:
Install-Package IronXL.Excel
Install-Package IronXL.Excel
請在表單檔案頂端加入所需的命名空間:
using IronXL;
using System.Data;
using IronXL;
using System.Data;
Imports IronXL
Imports System.Data
這兩個命名空間涵蓋了讀取和寫入 Excel 工作簿所需的所有 IronXL 類型,以及用於處理連接您的 System.Data 物件和 DataTable 到匯出管道的標準 DataGridView 類型的 @@CODE-9631--9631。
如何將範例資料載入 DataGridView 控制項?
在建立匯出邏輯之前,請用代表性資料填入您的 DataGridView。 Form1_Load 事件是綁定 DataTable 作為資料來源的正確位置。 在實際應用中,你會查詢資料庫或呼叫服務;這裡硬編碼的 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
此程式碼採用頂層陳述式風格來定義事件處理常式的簽名。 DataTable 有四列類型—整數、字串、十進位和整數—IronXL 在寫入 Excel 工作簿時會保留這些類型。 資料欄位的資料型別至關重要,因為 IronXL 會將數值欄位寫入為數值儲存格而非文字,這讓使用者能在 Excel 中直接對數值進行排序和求和,無需重新格式化。
C# DataGridView 匯出到 Excel 並保留格式:完整指南:圖 2 - 表單的 UI
DataGridView 根據 DataTable 列名自動渲染列標題行。 當您進行匯出時,希望 Excel 檔案中能保留該標題列,這意味著您的匯出程式碼必須將標題列與資料列分開處理——下一節將詳細說明這一點。
對於生產環境,無論 DataTable 來自 Entity Framework、Dapper、ADO.NET 或任何其他資料存取層,都適用相同的模式。 DataGridView 綁定與導出程式碼解耦,因此您可以切換資料來源而無需修改導出邏輯。
如何將 DataGridView 中的資料匯出至 Excel 檔案?
核心匯出邏輯在按鈕點擊處理程序中執行。 IronXL 在 WorkSheet 上提供了一個 LoadFromDataTable 方法,可以自動處理列到單元格的對應。 最簡潔的方法是從 DataGridView 中提取 DataTable 並直接傳遞。 Open XML SDK 是 .xlsx 格式的基礎,微軟對此進行了文件說明,並證實了為什麼像 IronXL 這樣的純 .NET 解決方案在程序化生成方面比 Interop 更勝一籌。
按鈕點擊匯出處理程序
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

LoadFromDataTable(dt, true) 呼叫接受 DataTable 和一個布林標誌,該標誌告訴 IronXL 將列名寫入 Excel 的第一行——這些列名將成為您的標題單元格。 工作簿使用 Environment.SpecialFolder.Desktop 而不是硬編碼路徑儲存到使用者的桌面,這使得程式碼可以在使用者帳戶之間移植。
null 檢查(?? 當儲存格不包含值時,會拋出 DBNull.Value) prevents a NullReferenceException 例外。 這對於實際資料而言至關重要,因為可選欄位可能為空。 IronXL 將DBNull` 寫入空單元格,而不是字串"DBNull",因此輸出保持乾淨。
有關將資料從 Excel 文件讀回 DataGridView 的更多詳細信息,請參閱IronXL DataTable 文檔,其中涵蓋了反向操作以及如何將 Excel 轉換為多工作表工作簿的 DataSet 。
如何對匯出的 Excel 檔案套用 Professional 格式?
Excel 檔案中的純文字資料雖具實用性,但 Professional 格式化的輸出——例如加粗標題、依內容調整欄寬、交替的行背景色——正是區分使用者信賴的工具,與那些必須匯出後立即手動重新格式化的工具的關鍵差異。 IronXL 提供豐富的儲存格樣式 API,涵蓋字型、顏色、邊框、數字格式及對齊方式。 OOXML 試算表樣式的規格定義了 IronXL 所寫入的底層格式,讓您能確信輸出檔可在任何符合規範的應用程式中正確開啟。
套用標題樣式與交錯行色彩
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
。
格式化代碼採用了多種技術手法。 標題行採用藍色背景(#4472C4),白色文本,12 號粗體字體,居中對齊——這是標準的商業電子表格樣式。 資料行每隔偶數行交替顯示白色和淺灰色(#D6DCE5),這樣使用者更容易在寬表格中閱讀而不會遺失位置。 "價格"欄位使用 Excel 內建的貨幣格式 ($#,##0.00),因此電子表格中的值會以美元符號和兩位小數顯示,而不會更改底層數值資料。 AutoSizeColumn 將每一列調整到最長值,因此不會截斷任何內容。
您可以進一步透過儲存格邊框樣式、條件格式化以及資料驗證規則來擴展此範例。 對於必須符合企業範本的報告,您亦可設定頁面版面配置與列印範圍,使匯出檔案無需調整即可直接列印。
您如何處理大型資料集與效能調校?
當 DataGridView 綁定到數千行時,逐個單元格迭代會變得明顯變慢。 兩項優化措施可顯著提升效能。 首先,使用 LoadFromDataTable 而不是每個單元格的 SetCellValue 呼叫。 其次,如果您的資料來源是 DataTable,請直接將其傳遞給 IronXL,而不是透過 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
對於超過 10,000 行的資料集,在後台執行緒上執行導出操作可以保持 UI 的響應性。將匯出邏輯包裝在 Task.Run 中,並使用 Invoke 將 MessageBox.Show 回呼序列化回 UI 執行緒。 IronXL 對獨立實例上的寫入操作是線程安全的,因此如果需要,您可以同時執行多個匯出操作。
其他效能相關資源:
在 DataGridView 匯出功能方面,IronXL 與 Microsoft Interop 相比如何?
許多開發者會從 Microsoft Excel Interop 開始使用,因為它隨 Office 一起提供,且無需額外安裝套件。 然而,Interop 存在實際成本,這些成本在生產環境中會迅速顯現。 下表概述了主要差異:
| 能力 | IronXL | Microsoft Interop |
|---|---|---|
| 需安裝 Microsoft Excel | 無 | 是 |
| 適用於伺服器/雲端環境 | 是 | 否(未獲 Microsoft 支援) |
| 需清理 COM 物件 | 無 | 是 (Marshal.ReleaseComObject) |
| 處理大型資料集的效能 | Fast (純 .NET) | 速度較慢(COM 序列化開銷) |
| 安裝方法 | NuGet | COM 參考 / Office 安裝 |
| 支援的 .NET 版本 | .NET 4.6.2 -- .NET 10 | 僅限 .NET Framework(功能有限) |
| 支援 XLSX、CSV、ODS 格式 | 是 | 僅限透過 Excel 處理 XLSX/XLS 檔案 |
微軟自身的文件已針對在伺服器或服務帳戶中使用 Office Interop 提出警告,理由是涉及穩定性與授權方面的考量。 IronXL 可在 Azure App Service、Windows 服務主機、Docker 容器,以及任何無法執行 Excel 等桌面應用程式的無頭環境中正常運作。
對於已經使用 Interop 並希望遷移的團隊來說,IronXL 的 API 映射非常接近,以至於大多數 WorkBook 和 WorkSheet 操作可以直接轉換。 《IronXL 遷移指南》涵蓋了常見的 Interop 模式及其在 IronXL 中的對應實現。
下一步計劃是什麼?
使用 IronXL 將 DataGridView 資料匯出至 Excel 只需要安裝 NuGet 套件和幾行程式碼,即可以乾淨、可維護的解決方案取代脆弱的 COM 互通方法,該解決方案可在任何部署環境中運作。 本文涵蓋的技術——基本匯出、格式化輸出、大型資料集優化以及比較表——將提供您所需的一切,以便在正式運作的 Windows Forms 應用程式中部署此功能。
由此探索以下相關功能:
- 使用 C# 從頭建立 Excel 檔案 -- 無需資料來源即可透過程式碼建立工作簿
- 將 Excel 檔案讀取至 DataTable —— 這是將 Excel 資料匯回應用程式中的反向操作
- 套用條件格式 -- 根據儲存格的數值自動標示
- 在 Excel 中設定圖表資料 -- 將圖表嵌入匯出的工作簿中
- 為 Excel 檔案設定密碼保護 -- 在分發前確保匯出報表的安全性
-匯出為 CSV 格式-- 當收件者需要平面檔案格式而非
.xlsx
立即開始免費試用 IronXL,在您的專案中測試完整功能集;若您已準備好進行生產環境部署,請查看 IronXL 的授權選項。
常見問題解答
如何在 C# 中將 DataGridView 數據匯出到 Excel?
透過 NuGet 安裝 IronXL,從 DataGridView 中擷取 DataTable,建立工作簿 (WorkBook) 和工作表 (WorkSheet),呼叫 worksheet.LoadFromDataTable(dt, true),然後使用 workbook.SaveAs 儲存。
將 DataGridView 匯出至 Excel 時,有哪些格式化選項可用?
IronXL 支援粗體字型、背景顏色、文字顏色、水平對齊、數字格式(例如貨幣)、欄位自動調整大小、邊框樣式以及條件格式化。
我需要安裝 Microsoft Excel 才能匯出 DataGridView 的資料嗎?
不。IronXL程式庫是一個純 .NET 程式庫,可在無需 Microsoft Office 或任何 COM 註冊的情況下,直接在電腦上產生 Excel 檔案。
匯出 DataGridView 到 Excel 時,可以樣式化標題嗎?
是的。撰寫完標題列後,請透過座標存取每個標題儲存格,並設定 Style.Font.Bold、Style.SetBackgroundColor 及 Style.Font.Color 屬性。
從 DataGridView 匯出時,如何在 Excel 中套用交替的行顏色?
在迭代 DataGridView 行時追蹤行索引,並對偶數行套用範圍樣式,方法是使用 worksheet[rangeAddress].Style.SetBackgroundColor 並指定您選擇的十六進位顏色。
將 DataGridView 匯出至 Excel 時,該如何處理大型資料集?
請將底層的 DataTable 直接傳遞給 worksheet.LoadFromDataTable,而非逐個迭代儲存格。若資料集非常龐大,請使用 Task.Run 在背景執行緒中執行匯出作業。
在 DataGridView 匯出功能方面,IronXL 與 Microsoft Excel Interop 相比如何?
IronXL 無需 Microsoft Excel 即可運作,適用於伺服器與雲端環境,無需 COM 清理程式碼,且在處理大型資料集時效能顯著提升。


