跳過到頁腳內容
使用 IRONXL

在 C# 中如何將一組對象導出到 Excel

IronXL 讓開發者可以在 C# 中將 List 物件直接匯出到 Excel 文件,無需依賴 MS Office,並透過簡單的 ImportData 方法自動處理類型轉換和屬性映射,將集合轉化為專業的 XLSX 試算表。

在商業應用中,匯出物件集合到 Excel 文件是一個基礎要求。 無論您是在生成報告、共享見解還是創建備份,您都需要一種可靠的方法將 List<t> 物件轉換為專業的試算表。 IronXL 提供了一個精簡的解決方案,消除了在 .NET, .NET Core 或 .NET Framework 中創建 Excel 文件的傳統複雜性。

為何將清單匯出到 Excel 文件具有挑戰性?

傳統上將資料匯出到 Excel 通常涉及 Microsoft Office Interop,這需要在伺服器上安裝 Excel,並造成部署上的困擾。 使用反射逐個儲存格手動填充是耗時且容易出錯的。 IronXL 強大的數據導入功能 解決了這些問題,通過在資料來源和 Excel 欄標題之間進行智能屬性映射,無需 MS Office 或複雜的反射代碼。

程式庫自動處理類型轉換,支援巢狀物件,並在不同格式(如 CSV 文件和 XLSX 文件)之間維護資料完整性。 對於使用 C# Excel 操作而無互操作 的開發者來說,IronXL 是現代 .NET 專案理想的選擇,提供強大的 Excel 生成和數據導入/導出的能力。 程式庫無縫整合 .NET MAUI 應用程式,並支持部署到 AzureAWS 雲平台。

在處理大型數據集時,傳統方法經常在內存管理和性能上遇到困難。 IronXL 透過優化的內部數據結構解決了這些問題,能夠有效處理 不同試算表格式之間的轉換,同時保持出色的性能特性。

如何將簡單的清單數據匯出到 Excel?

開始使用 IronXL 所需設定非常少。首先,通過 NuGet 套件管理器主控台安裝程式庫:

Install-Package IronXL.Excel

安裝後,您可以立即從 C# 數據結構中 創建 Excel 試算表。 讓我們來探索如何使用員工模型匯出數據:

using IronXL;
using System.Collections.Generic;
using System.Data;
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
    public DateTime HireDate { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        // Create sample data for Excel export
        var employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Alice Johnson", Department = "Engineering",
                           Salary = 95000, HireDate = new DateTime(2020, 3, 15) },
            new Employee { Id = 2, Name = "Bob Smith", Department = "Marketing",
                           Salary = 75000, HireDate = new DateTime(2021, 7, 1) },
            new Employee { Id = 3, Name = "Carol Williams", Department = "Engineering",
                           Salary = 105000, HireDate = new DateTime(2019, 11, 20) }
        };
        // Convert the list of employees to a DataTable
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("Id", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Columns.Add("Department", typeof(string));
        dataTable.Columns.Add("Salary", typeof(decimal));
        dataTable.Columns.Add("HireDate", typeof(DateTime));
        foreach (var employee in employees)
        {
            dataTable.Rows.Add(employee.Id, employee.Name, employee.Department, employee.Salary, employee.HireDate);
        }
        // Export DataTable to Excel spreadsheet
        var workbook = new WorkBook();
        var worksheet = workbook.CreateWorkSheet("Employees");
        // Populate the worksheet
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            worksheet.SetCellValue(0, i, dataTable.Columns[i].ColumnName); // Add column headers
        }
        for (int i = 0; i < dataTable.Rows.Count; i++)
        {
            for (int j = 0; j < dataTable.Columns.Count; j++)
            {
                worksheet.SetCellValue(i + 1, j, dataTable.Rows[i][j]); // Add data rows
            }
        }
        // Save as XLSX file
        workbook.SaveAs("EmployeeReport.xlsx");
    }
}
using IronXL;
using System.Collections.Generic;
using System.Data;
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
    public DateTime HireDate { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        // Create sample data for Excel export
        var employees = new List<Employee>
        {
            new Employee { Id = 1, Name = "Alice Johnson", Department = "Engineering",
                           Salary = 95000, HireDate = new DateTime(2020, 3, 15) },
            new Employee { Id = 2, Name = "Bob Smith", Department = "Marketing",
                           Salary = 75000, HireDate = new DateTime(2021, 7, 1) },
            new Employee { Id = 3, Name = "Carol Williams", Department = "Engineering",
                           Salary = 105000, HireDate = new DateTime(2019, 11, 20) }
        };
        // Convert the list of employees to a DataTable
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("Id", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Columns.Add("Department", typeof(string));
        dataTable.Columns.Add("Salary", typeof(decimal));
        dataTable.Columns.Add("HireDate", typeof(DateTime));
        foreach (var employee in employees)
        {
            dataTable.Rows.Add(employee.Id, employee.Name, employee.Department, employee.Salary, employee.HireDate);
        }
        // Export DataTable to Excel spreadsheet
        var workbook = new WorkBook();
        var worksheet = workbook.CreateWorkSheet("Employees");
        // Populate the worksheet
        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            worksheet.SetCellValue(0, i, dataTable.Columns[i].ColumnName); // Add column headers
        }
        for (int i = 0; i < dataTable.Rows.Count; i++)
        {
            for (int j = 0; j < dataTable.Columns.Count; j++)
            {
                worksheet.SetCellValue(i + 1, j, dataTable.Rows[i][j]); // Add data rows
            }
        }
        // Save as XLSX file
        workbook.SaveAs("EmployeeReport.xlsx");
    }
}
$vbLabelText   $csharpLabel

此範例代碼顯示了如何使用 IronXL 將數據從 List<Employee> 匯出到 Excel。 它首先將員工清單轉換為 DataTable,然後手動將列標題和行寫入工作表中。 IronXL 自動處理如 int、string 和 DateTime 等數據類型,保證在生成的試算表中有良好的格式。 最後,Excel 保存功能生成一個名為 EmployeeReport.xlsx 的 XLSX 文件,提供簡單而有效的方式將結構化 C# 數據轉換為專業 Excel 報告

上述的方法表現了一個基礎模式,可以擴展為更複雜的場景。 例如,您可能需要從現有的數據庫查詢中 匯出 datasets 和 datatables,或從外部源 導入 Excel 數據。 IronXL 提供了針對這兩種場景的全面方法,使其成為資料交換操作的多功能工具。

Excel 試算表顯示已匯出的員工數據,包含 Id、名稱、部門、薪水和雇用日期欄,顯示 3 個範例員工記錄,格式良好

如何匯出複雜的商業物件?

真實世界的 .NET 應用程式通常涉及更複雜的數據結構。 在處理巢狀屬性、計算欄位或層次數據時,您需要更為複雜的方法。 IronXL 擅長處理這些場景,提供在多種格式下 處理數據 的強大支持。 這是如何匯出帶巢狀屬性的產品庫存:

using IronXL;
using System.Collections.Generic;
using System.Data;
public class Product
{
    public string SKU { get; set; }
    public string ProductName { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public int StockLevel { get; set; }
    public bool IsActive { get; set; }
    public DateTime LastRestocked { get; set; }
    public decimal CalculatedValue => Price * StockLevel;
}
class Program
{
    static void Main(string[] args)
    {
        // Generate product inventory list for Excel export
        var products = new List<Product>
        {
            new Product
            {
                SKU = "TECH-001",
                ProductName = "Wireless Mouse",
                Category = "Electronics",
                Price = 29.99m,
                StockLevel = 150,
                IsActive = true,
                LastRestocked = DateTime.Now.AddDays(-5)
            },
            new Product
            {
                SKU = "TECH-002",
                ProductName = "Mechanical Keyboard",
                Category = "Electronics",
                Price = 89.99m,
                StockLevel = 75,
                IsActive = true,
                LastRestocked = DateTime.Now.AddDays(-12)
            },
            new Product
            {
                SKU = "OFF-001",
                ProductName = "Desk Organizer",
                Category = "Office Supplies",
                Price = 15.99m,
                StockLevel = 0,
                IsActive = false,
                LastRestocked = DateTime.Now.AddMonths(-1)
            }
        };
        // Create Excel workbook and import collection data
        var workbook = WorkBook.Create();
        var worksheet = workbook.CreateWorkSheet("Inventory");
        // Export generic list to Excel with headers
        var dataTable = new DataTable();
        dataTable.Columns.Add("SKU", typeof(string));
        dataTable.Columns.Add("ProductName", typeof(string));
        dataTable.Columns.Add("Category", typeof(string));
        dataTable.Columns.Add("Price", typeof(decimal));
        dataTable.Columns.Add("StockLevel", typeof(int));
        dataTable.Columns.Add("IsActive", typeof(bool));
        dataTable.Columns.Add("LastRestocked", typeof(DateTime));
        dataTable.Columns.Add("CalculatedValue", typeof(decimal));
        foreach (var product in products)
        {
            dataTable.Rows.Add(
                product.SKU,
                product.ProductName,
                product.Category,
                product.Price,
                product.StockLevel,
                product.IsActive,
                product.LastRestocked,
                product.CalculatedValue
            );
        }
        // With the following code:
        worksheet["A1"].Value = "SKU";
        worksheet["B1"].Value = "ProductName";
        worksheet["C1"].Value = "Category";
        worksheet["D1"].Value = "Price";
        worksheet["E1"].Value = "StockLevel";
        worksheet["F1"].Value = "IsActive";
        worksheet["G1"].Value = "LastRestocked";
        worksheet["H1"].Value = "CalculatedValue";
        int row = 2;
        foreach (DataRow dataRow in dataTable.Rows)
        {
            worksheet[$"A{row}"].Value = dataRow["SKU"];
            worksheet[$"B{row}"].Value = dataRow["ProductName"];
            worksheet[$"C{row}"].Value = dataRow["Category"];
            worksheet[$"D{row}"].Value = dataRow["Price"];
            worksheet[$"E{row}"].Value = dataRow["StockLevel"];
            worksheet[$"F{row}"].Value = dataRow["IsActive"];
            worksheet[$"G{row}"].Value = dataRow["LastRestocked"];
            worksheet[$"H{row}"].Value = dataRow["CalculatedValue"];
            row++;
        }
        // Auto-fit columns for optimal display
        for (int col = 0; col < 8; col++)
        {
            worksheet.AutoSizeColumn(col);
        }
        // Save as Excel XLSX format
        workbook.SaveAs("ProductInventory.xlsx");
    }
}
using IronXL;
using System.Collections.Generic;
using System.Data;
public class Product
{
    public string SKU { get; set; }
    public string ProductName { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public int StockLevel { get; set; }
    public bool IsActive { get; set; }
    public DateTime LastRestocked { get; set; }
    public decimal CalculatedValue => Price * StockLevel;
}
class Program
{
    static void Main(string[] args)
    {
        // Generate product inventory list for Excel export
        var products = new List<Product>
        {
            new Product
            {
                SKU = "TECH-001",
                ProductName = "Wireless Mouse",
                Category = "Electronics",
                Price = 29.99m,
                StockLevel = 150,
                IsActive = true,
                LastRestocked = DateTime.Now.AddDays(-5)
            },
            new Product
            {
                SKU = "TECH-002",
                ProductName = "Mechanical Keyboard",
                Category = "Electronics",
                Price = 89.99m,
                StockLevel = 75,
                IsActive = true,
                LastRestocked = DateTime.Now.AddDays(-12)
            },
            new Product
            {
                SKU = "OFF-001",
                ProductName = "Desk Organizer",
                Category = "Office Supplies",
                Price = 15.99m,
                StockLevel = 0,
                IsActive = false,
                LastRestocked = DateTime.Now.AddMonths(-1)
            }
        };
        // Create Excel workbook and import collection data
        var workbook = WorkBook.Create();
        var worksheet = workbook.CreateWorkSheet("Inventory");
        // Export generic list to Excel with headers
        var dataTable = new DataTable();
        dataTable.Columns.Add("SKU", typeof(string));
        dataTable.Columns.Add("ProductName", typeof(string));
        dataTable.Columns.Add("Category", typeof(string));
        dataTable.Columns.Add("Price", typeof(decimal));
        dataTable.Columns.Add("StockLevel", typeof(int));
        dataTable.Columns.Add("IsActive", typeof(bool));
        dataTable.Columns.Add("LastRestocked", typeof(DateTime));
        dataTable.Columns.Add("CalculatedValue", typeof(decimal));
        foreach (var product in products)
        {
            dataTable.Rows.Add(
                product.SKU,
                product.ProductName,
                product.Category,
                product.Price,
                product.StockLevel,
                product.IsActive,
                product.LastRestocked,
                product.CalculatedValue
            );
        }
        // With the following code:
        worksheet["A1"].Value = "SKU";
        worksheet["B1"].Value = "ProductName";
        worksheet["C1"].Value = "Category";
        worksheet["D1"].Value = "Price";
        worksheet["E1"].Value = "StockLevel";
        worksheet["F1"].Value = "IsActive";
        worksheet["G1"].Value = "LastRestocked";
        worksheet["H1"].Value = "CalculatedValue";
        int row = 2;
        foreach (DataRow dataRow in dataTable.Rows)
        {
            worksheet[$"A{row}"].Value = dataRow["SKU"];
            worksheet[$"B{row}"].Value = dataRow["ProductName"];
            worksheet[$"C{row}"].Value = dataRow["Category"];
            worksheet[$"D{row}"].Value = dataRow["Price"];
            worksheet[$"E{row}"].Value = dataRow["StockLevel"];
            worksheet[$"F{row}"].Value = dataRow["IsActive"];
            worksheet[$"G{row}"].Value = dataRow["LastRestocked"];
            worksheet[$"H{row}"].Value = dataRow["CalculatedValue"];
            row++;
        }
        // Auto-fit columns for optimal display
        for (int col = 0; col < 8; col++)
        {
            worksheet.AutoSizeColumn(col);
        }
        // Save as Excel XLSX format
        workbook.SaveAs("ProductInventory.xlsx");
    }
}
$vbLabelText   $csharpLabel

此代碼顯示如何使用 IronXL 在 Excel 中生成動態產品庫存報告。 它構建了一個產品物件清單,其中包含 SKU、價格、庫存水平和再進貨日期等細節,然後為每個項目計算一個派生的 CalculatedValue。 數據被轉換為 DataTable,並寫入具有標題的 Excel 工作表中,並使用自動調整大小的欄位進行可讀性格式化。 IronXL 無縫處理如小數、布林和日期等數據類型,确保專業的試算表輸出。 結果 ProductInventory.xlsx 提供了乾淨的、數據驅動的庫存匯出,非常適合業務報告或分析。

在處理複雜物件時,您可能還需要為不同數據類別 管理工作表,或者在一個工作簿中 創建多個工作表。 IronXL 支持高級工作表操作,允許您合理地組織匯出的數據。 此外,您可以 選擇特定範圍 用於目標數據操作,或 排序儲存格以便以有意義的順序呈現數據。

Excel 試算表顯示產品庫存匯出,包含 SKU、產品名稱、類別、價格、庫存水平、是否啟用狀態、上次進貨日期和計算值,顯示各種電子產品和辦公用品

如何新增專業格式化?

使用 IronXL 的全面樣式功能將基本匯出轉變為精美的報告。 專業格式化使您的 Excel 匯出從簡單的數據轉儲提升為可有效傳達見解的高階報告。 IronXL 提供了豐富的格式化選項,包括 儲存格字體和字體大小定制、背景樣式和顏色邊框對齊設置:

// After importing data, apply professional formatting
var headerRange = worksheet["A1:H1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.BackgroundColor = "#4472C4";
headerRange.Style.Font.Color = "#FFFFFF";
// Format currency columns for Excel export
var priceColumn = worksheet["D2:D100"];
priceColumn.Style.NumberFormat = "$#,##0.00";
// Apply conditional formatting to highlight business metrics
for (int row = 2; row <= products.Count + 1; row++)
{
    var stockCell = worksheet[$"E{row}"];
    if (stockCell.IntValue < 10)
    {
        stockCell.Style.BackgroundColor = "#FF6B6B";
    }
}
// Export formatted list to Excel file
workbook.SaveAs("FormattedInventory.xlsx");
// After importing data, apply professional formatting
var headerRange = worksheet["A1:H1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.BackgroundColor = "#4472C4";
headerRange.Style.Font.Color = "#FFFFFF";
// Format currency columns for Excel export
var priceColumn = worksheet["D2:D100"];
priceColumn.Style.NumberFormat = "$#,##0.00";
// Apply conditional formatting to highlight business metrics
for (int row = 2; row <= products.Count + 1; row++)
{
    var stockCell = worksheet[$"E{row}"];
    if (stockCell.IntValue < 10)
    {
        stockCell.Style.BackgroundColor = "#FF6B6B";
    }
}
// Export formatted list to Excel file
workbook.SaveAs("FormattedInventory.xlsx");
$vbLabelText   $csharpLabel

這些樣式選項將原始數據匯出轉變為高階報告。 帶有背景顏色的粗體標題在匯出集合到 Excel 時創建了視覺階層。 數字格式化保證貨幣值以專業方式顯示。 條件格式化突出顯示關鍵業務指標,例如庫存水平過低,使匯出的 Excel 試算表對於庫存管理立即具有效用。 了解更多 高級儲存格式化邊框樣式以進一步提升您的匯出效果。

除了基本格式化外,IronXL 還支持高級功能如 創建 Excel 圖表來視覺化您的匯出數據。 您還可以 添加超鏈接來連接相關數據點或外部資源,凍結窗格以便更好地瀏覽大型數據集,甚至 合併儲存格以創建複雜的報告佈局。

Excel 庫存試算表顯示專業格式化,包含 SKU、產品名稱、類別、價格、庫存水平,在條件格式化下以紅色突出顯示零庫存,是否啟用狀態、上次進貨日期和計算值欄

如何開始使用 IronXL 是最佳方式?

IronXL 將複雜的 Excel 生成任務轉變為簡單且易於維護的程式碼。 其智能 ImportData 方法消除了 MS Office 依賴的需求,同時提供符合企業需求的專業結果。 程式庫的全面功能集從基本清單匯出到複雜數據轉換涵蓋一切,並具有樣式和格式化功能。

開始使用 IronXL 是直觀的。 程式庫支持各種部署場景,包括 Docker 容器Linux 環境macOS 系統。 對於企業部署,IronXL 提供 全面的授權選項,具有靈活的 授權金鑰管理

程式庫在資料交換操作上也表現優異。 您可以 將 XLSX 轉換為 CSV寫入 CSV 文件閱讀 CSV 數據,甚至 將 DataTables 轉換為 CSV 格式。 對於 Web 應用,IronXL 可無縫整合 ASP.NET MVCBlazor 框架。

使用現有的 Excel 文件時,IronXL 提供了強大的功能來 編輯 Excel 文件打開工作表,以及 讀取 XLSX 文件。 如果您的專案需要 Visual Basic 整合,您還可以使用 VB.NET Excel 文件

現在開始使用 IronXL。
green arrow pointer

準備好簡化您的 C# Excel 匯出操作了嗎? 立即下載 IronXL 以實現您的需求規模。 訪問我們的 全面文檔以獲取更多教程和範例。 探索 API 參考以獲取詳細技術規格,並了解 IronXL 如何改變您的 Excel 自動化工作流程。

常見問題解答

IronXL 的主要功能是什麼?

IronXL 提供了一個簡化的解決方案,將對象集合(例如 List)導出到 .NET 環境中的 Excel 檔案,而無需傳統方法的複雜性。

IronXL 如何簡化資料到 Excel 的導出?

IronXL 通過提供 ImportData 方法來簡化過程,開發人員可以輕鬆地將 C# 列表和複雜物件轉換為專業的 Excel 試算表,而不需要 Office Interop。

IronXL 可以與 .NET Core 一起使用嗎?

是的,IronXL 兼容 .NET Core,以及 .NET 和 .NET Framework,使其在各種開發環境中具有靈活性。

使用 IronXL 時需要 Office Interop 嗎?

不,IronXL 不需要 Office Interop,這簡化了過程並減少了導出資料到 Excel 時的依賴。

IronXL 可以導出哪些類型的 C# 列表?

IronXL 可以將通用列表和複雜物件導出到 Excel,為開發人員處理各種資料結構提供靈活的選擇。

為什麼將資料導出到 Excel 對業務應用程式很重要?

將資料導出到 Excel 是生成報表、共享見解和創建備份的關鍵,這些都是有效業務運營和決策制定的基礎。

IronXL 支持創建專業試算表嗎?

是的,IronXL 設計用於將 C# 列表轉換為專業品質的 Excel 試算表,適合業務報告和資料分析。

IronXL 提供了什麼優勢,超越了傳統的 Excel 文件創建方法?

IronXL 消除了創建 Excel 文件時的傳統複雜性和依賴,為開發人員提供了一種更高效且可靠的方法。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

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