跳至页脚内容
使用 IRONXL

如何在 C# 中将对象列表导出到 Excel

Exporting collections of objects to Excel files is a fundamental requirement in business applications. Whether generating reports, exporting data to share insights, or creating Excel worksheets for backups, developers need a reliable way to transform List<T> objects into professional spreadsheets. IronXL provides a streamlined solution that eliminates the traditional complexities of creating Excel files in .NET, .NET Core, or the .NET Framework.

Why Is Exporting Lists to Excel Files Challenging?

Traditional approaches to export data to Excel often involve Microsoft Office Interop, which requires MS Excel installation on the server and creates deployment headaches. Manual cell-by-cell population using reflection is time-consuming and error-prone. IronXL's powerful data import features solve these problems with intelligent property mapping between data sources and Excel column headers, without requiring MS Office or complex reflection code.

The library handles type conversion automatically, supports nested objects, and maintains data integrity across different formats like CSV files and XLSX files. For developers working with C# Excel operations without Interop, IronXL is the ideal choice for modern .NET projects that need robust Excel generation and data import/export capabilities.

How to Export Simple List Data to Excel?

Getting started with IronXL requires minimal setup. First, install the library through the NuGet Package Manager Console:

Install-Package IronXL.Excel

In the following code example, we'll explore how you can export data using an Employee model:

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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This sample code demonstrates how to export data to Excel from a List<Employee> using IronXL. It first converts the employee list into a DataTable, then manually writes column headers and rows into a worksheet. IronXL handles data types like int, string, and DateTime data types automatically, ensuring clean formatting in the generated spreadsheet. Finally, the Excel save function produces an XLSX file, which can be saved as EmployeeReport.xlsx, providing a simple and efficient way to turn structured C# data into a professional Excel report.

How to Export a List of Objects to Excel in C#: Figure 1

How to Export Complex Business Objects?

Real-world .NET applications often involve more complex data structures. Here’s how to export a product inventory with nested properties, using C# export list of objects to Excel:

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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code demonstrates how to generate a dynamic product inventory report in Excel using IronXL. It builds a list of Product objects containing details like SKU, price, stock level, and restock date, then calculates a derived CalculatedValue for each item. The data is converted into a DataTable, written to an Excel worksheet with headers, and formatted for readability using auto-sized columns. IronXL seamlessly handles data types such as decimals, booleans, and dates, ensuring professional spreadsheet output. The result, ProductInventory.xlsx, provides a clean, data-driven inventory export ideal for business reporting or analytics.

How to Export a List of Objects to Excel in C#: Figure 2 - Example output for complex business objects

How to Add Professional Formatting?

Transform basic exports into polished reports with IronXL's comprehensive styling capabilities:

// 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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These styling options transform raw data exports into executive-ready reports. Bold headers with background colors create visual hierarchy when exporting collections to Excel. Number formatting ensures currency values display professionally. Conditional formatting highlights critical business metrics, such as low stock levels, making the exported Excel spreadsheet immediately actionable for inventory management. Learn more about advanced cell formatting and border styles to enhance your exports further.

How to Export a List of Objects to Excel in C#: Figure 3 - Formatted worksheet

Start Exporting Lists to Excel Today

IronXL transforms the complex task of Excel generation into simple, maintainable code. Its intelligent ImportData method eliminates the need for Microsoft Office dependencies while providing professional results that meet enterprise requirements. The library's comprehensive feature set handles everything from basic list exports to complex data transformations with styling and formatting.

立即开始使用 IronXL。
green arrow pointer

Ready to streamline your C# Excel exports? Download IronXL now that scale with your needs. Visit our comprehensive documentation for more tutorials and examples.

常见问题解答

IronXL 的主要功能是什么?

IronXL 为在.NET环境中将对象集合(如List)导出到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时的依赖性。

哪些类型的C#列表可以使用IronXL导出?

IronXL既可以导出通用列表,也可以导出复杂的对象,为开发人员处理各种数据结构提供了灵活的选择。

为什么将数据导出到Excel对业务应用程序很重要?

导出数据到Excel对于生成报告、共享见解和创建备份至关重要,这些都是有效业务运营和决策的基础。

IronXL是否支持创建专业的电子表格?

是的,IronXL旨在将C#列表转化为专业质量的Excel电子表格,适用于业务报告和数据分析。

IronXL 比传统的 Excel 文件创建方法有什么好处?

IronXL 消除了创建 Excel 文件所涉及的传统复杂性和依赖性,为开发人员提供了一种更高效和可靠的方法。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。