Skip to footer content
USING IRONXL

C# Export List Object to Excel

Exporting collections of objects to Excel files is a fundamental requirement in business applications. Whether generating reports, sharing data insights, or creating Excel worksheets for backups, developers need a reliable way to transform List<T> objects into professional spreadsheets. IronXL delivers a solution that eliminates the traditional difficulties of creating Excel files in .NET 10, .NET Core, or the .NET Framework -- without requiring Microsoft Office on the server.

Why Is Exporting Lists to Excel Files Challenging?

Traditional approaches for exporting 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 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 on C# Excel operations without Interop, IronXL is the ideal choice for modern .NET projects that need reliable Excel generation and data import/export capabilities.

How Does IronXL Simplify Object Export?

IronXL removes the need for COM registration, Office licenses, and interop assemblies. When you export a List<T> to Excel, the library:

  • Maps object properties directly to column headers
  • Converts .NET types (DateTime, decimal, bool) to their correct Excel representations
  • Allows fine-grained control over cell values, ranges, and formatting
  • Saves output in XLSX, XLS, CSV, and other formats with a single method call

This approach means you get clean, professional spreadsheet output without writing hundreds of lines of boilerplate code. You can also import data back from Excel later, making round-trip data workflows straightforward.

How Do You Install IronXL?

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

Install-Package IronXL
Install-Package IronXL
SHELL

Or use the .NET CLI:

dotnet add package IronXL
dotnet add package IronXL
SHELL

Once installed, add the using IronXL; directive to your file. No additional Office dependencies or runtime installations are required.

How Do You Export a Simple List to Excel?

The following example demonstrates exporting a list of Employee objects to an XLSX file using top-level statements, the preferred style in .NET 10:

using IronXL;
using System.Data;

// Define the Employee model
record Employee(int Id, string Name, string Department, decimal Salary, DateTime HireDate);

// Create sample employee data
List<Employee> employees =
[
    new(1, "Alice Johnson", "Engineering", 95000, new DateTime(2020, 3, 15)),
    new(2, "Bob Smith",    "Marketing",   75000, new DateTime(2021, 7, 1)),
    new(3, "Carol Williams","Engineering",105000, new DateTime(2019, 11, 20))
];

// Build a DataTable from the list
DataTable dataTable = new();
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 emp in employees)
    dataTable.Rows.Add(emp.Id, emp.Name, emp.Department, emp.Salary, emp.HireDate);

// Create an IronXL workbook and worksheet
WorkBook workbook  = new();
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");

// Write headers
for (int col = 0; col < dataTable.Columns.Count; col++)
    worksheet.SetCellValue(0, col, dataTable.Columns[col].ColumnName);

// Write data rows
for (int row = 0; row < dataTable.Rows.Count; row++)
    for (int col = 0; col < dataTable.Columns.Count; col++)
        worksheet.SetCellValue(row + 1, col, dataTable.Rows[row][col]);

// Save as XLSX
workbook.SaveAs("EmployeeReport.xlsx");
Console.WriteLine("EmployeeReport.xlsx saved.");
using IronXL;
using System.Data;

// Define the Employee model
record Employee(int Id, string Name, string Department, decimal Salary, DateTime HireDate);

// Create sample employee data
List<Employee> employees =
[
    new(1, "Alice Johnson", "Engineering", 95000, new DateTime(2020, 3, 15)),
    new(2, "Bob Smith",    "Marketing",   75000, new DateTime(2021, 7, 1)),
    new(3, "Carol Williams","Engineering",105000, new DateTime(2019, 11, 20))
];

// Build a DataTable from the list
DataTable dataTable = new();
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 emp in employees)
    dataTable.Rows.Add(emp.Id, emp.Name, emp.Department, emp.Salary, emp.HireDate);

// Create an IronXL workbook and worksheet
WorkBook workbook  = new();
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");

// Write headers
for (int col = 0; col < dataTable.Columns.Count; col++)
    worksheet.SetCellValue(0, col, dataTable.Columns[col].ColumnName);

// Write data rows
for (int row = 0; row < dataTable.Rows.Count; row++)
    for (int col = 0; col < dataTable.Columns.Count; col++)
        worksheet.SetCellValue(row + 1, col, dataTable.Rows[row][col]);

// Save as XLSX
workbook.SaveAs("EmployeeReport.xlsx");
Console.WriteLine("EmployeeReport.xlsx saved.");
$vbLabelText   $csharpLabel

This example converts a List<Employee> into a DataTable, then writes headers and rows into an IronXL worksheet. IronXL handles data types like int, string, and DateTime automatically, ensuring clean formatting in the generated spreadsheet. The Excel save function produces an XLSX file ready to open in any spreadsheet application.

C# Export List of Objects to Excel with IronXL: Image 1 - Image 1 of 3 related to C# Export List of Objects to Excel with IronXL

How Do You Export Complex Business Objects?

Real-world .NET applications often involve more complex data structures. The following example generates a product inventory report with a calculated property:

using IronXL;
using System.Data;

// Define the Product model with a computed property
record Product(
    string SKU,
    string ProductName,
    string Category,
    decimal Price,
    int StockLevel,
    bool IsActive,
    DateTime LastRestocked)
{
    public decimal CalculatedValue => Price * StockLevel;
}

// Build the product list
List<Product> products =
[
    new("TECH-001", "Wireless Mouse",      "Electronics",     29.99m, 150, true,  DateTime.Now.AddDays(-5)),
    new("TECH-002", "Mechanical Keyboard", "Electronics",     89.99m,  75, true,  DateTime.Now.AddDays(-12)),
    new("OFF-001",  "Desk Organizer",      "Office Supplies", 15.99m,   0, false, DateTime.Now.AddMonths(-1))
];

// Populate a DataTable
DataTable dt = new();
dt.Columns.Add("SKU",             typeof(string));
dt.Columns.Add("ProductName",     typeof(string));
dt.Columns.Add("Category",        typeof(string));
dt.Columns.Add("Price",           typeof(decimal));
dt.Columns.Add("StockLevel",      typeof(int));
dt.Columns.Add("IsActive",        typeof(bool));
dt.Columns.Add("LastRestocked",   typeof(DateTime));
dt.Columns.Add("CalculatedValue", typeof(decimal));

foreach (var p in products)
    dt.Rows.Add(p.SKU, p.ProductName, p.Category, p.Price,
                p.StockLevel, p.IsActive, p.LastRestocked, p.CalculatedValue);

// Create the workbook
WorkBook  wb = WorkBook.Create();
WorkSheet ws = wb.CreateWorkSheet("Inventory");

// Write column headers
string[] headers = ["SKU","ProductName","Category","Price",
                    "StockLevel","IsActive","LastRestocked","CalculatedValue"];
for (int col = 0; col < headers.Length; col++)
    ws.SetCellValue(0, col, headers[col]);

// Write data rows
for (int row = 0; row < dt.Rows.Count; row++)
    for (int col = 0; col < dt.Columns.Count; col++)
        ws.SetCellValue(row + 1, col, dt.Rows[row][col]);

// Auto-size columns for readability
for (int col = 0; col < headers.Length; col++)
    ws.AutoSizeColumn(col);

wb.SaveAs("ProductInventory.xlsx");
Console.WriteLine("ProductInventory.xlsx saved.");
using IronXL;
using System.Data;

// Define the Product model with a computed property
record Product(
    string SKU,
    string ProductName,
    string Category,
    decimal Price,
    int StockLevel,
    bool IsActive,
    DateTime LastRestocked)
{
    public decimal CalculatedValue => Price * StockLevel;
}

// Build the product list
List<Product> products =
[
    new("TECH-001", "Wireless Mouse",      "Electronics",     29.99m, 150, true,  DateTime.Now.AddDays(-5)),
    new("TECH-002", "Mechanical Keyboard", "Electronics",     89.99m,  75, true,  DateTime.Now.AddDays(-12)),
    new("OFF-001",  "Desk Organizer",      "Office Supplies", 15.99m,   0, false, DateTime.Now.AddMonths(-1))
];

// Populate a DataTable
DataTable dt = new();
dt.Columns.Add("SKU",             typeof(string));
dt.Columns.Add("ProductName",     typeof(string));
dt.Columns.Add("Category",        typeof(string));
dt.Columns.Add("Price",           typeof(decimal));
dt.Columns.Add("StockLevel",      typeof(int));
dt.Columns.Add("IsActive",        typeof(bool));
dt.Columns.Add("LastRestocked",   typeof(DateTime));
dt.Columns.Add("CalculatedValue", typeof(decimal));

foreach (var p in products)
    dt.Rows.Add(p.SKU, p.ProductName, p.Category, p.Price,
                p.StockLevel, p.IsActive, p.LastRestocked, p.CalculatedValue);

// Create the workbook
WorkBook  wb = WorkBook.Create();
WorkSheet ws = wb.CreateWorkSheet("Inventory");

// Write column headers
string[] headers = ["SKU","ProductName","Category","Price",
                    "StockLevel","IsActive","LastRestocked","CalculatedValue"];
for (int col = 0; col < headers.Length; col++)
    ws.SetCellValue(0, col, headers[col]);

// Write data rows
for (int row = 0; row < dt.Rows.Count; row++)
    for (int col = 0; col < dt.Columns.Count; col++)
        ws.SetCellValue(row + 1, col, dt.Rows[row][col]);

// Auto-size columns for readability
for (int col = 0; col < headers.Length; col++)
    ws.AutoSizeColumn(col);

wb.SaveAs("ProductInventory.xlsx");
Console.WriteLine("ProductInventory.xlsx saved.");
$vbLabelText   $csharpLabel

This code builds a list of Product objects containing details like SKU, price, stock level, and restock date, then calculates a derived CalculatedValue for each item. IronXL handles data types such as decimals, booleans, and dates, ensuring professional spreadsheet output. The result, ProductInventory.xlsx, provides a clean, data-driven inventory export suitable for business reporting or analytics. You can also export a DataTable to Excel directly if your existing codebase already works with DataTable objects.

C# Export List of Objects to Excel with IronXL: Image 2 - Example output for complex business objects

How Do You Control Column Width and Row Height?

After writing data, you can control the visual layout of the spreadsheet programmatically. IronXL's AutoSizeColumn method adjusts each column to fit its content. Alternatively, you can set explicit column widths or add and remove rows and columns to adjust the sheet structure before saving.

For row height, IronXL exposes row-level properties that let you set a fixed pixel height -- useful when the worksheet will be printed or shared as a PDF. Consistent column and row sizing also improves readability when the Excel file is opened on different screen resolutions or printed at different scales, which is particularly important for reports distributed to external stakeholders.

How Do You Add Professional Formatting?

Formatting transforms basic exports into polished reports. IronXL's styling API exposes font, color, border, and number format settings on any cell or range:

using IronXL;

WorkBook  wb = WorkBook.Load("ProductInventory.xlsx");
WorkSheet ws = wb.DefaultWorkSheet;

// Bold header row with a blue background and white text
Range headerRange = ws["A1:H1"];
headerRange.Style.Font.Bold            = true;
headerRange.Style.BackgroundColor      = "#4472C4";
headerRange.Style.Font.Color           = "#FFFFFF";

// Format the Price column as currency
Range priceColumn = ws["D2:D100"];
priceColumn.Style.NumberFormat = "$#,##0.00";

// Highlight low-stock rows in red
for (int row = 2; row <= 4; row++)
{
    var stockCell = ws[$"E{row}"];
    if (stockCell.IntValue < 10)
        stockCell.Style.BackgroundColor = "#FF6B6B";
}

wb.SaveAs("FormattedInventory.xlsx");
Console.WriteLine("FormattedInventory.xlsx saved.");
using IronXL;

WorkBook  wb = WorkBook.Load("ProductInventory.xlsx");
WorkSheet ws = wb.DefaultWorkSheet;

// Bold header row with a blue background and white text
Range headerRange = ws["A1:H1"];
headerRange.Style.Font.Bold            = true;
headerRange.Style.BackgroundColor      = "#4472C4";
headerRange.Style.Font.Color           = "#FFFFFF";

// Format the Price column as currency
Range priceColumn = ws["D2:D100"];
priceColumn.Style.NumberFormat = "$#,##0.00";

// Highlight low-stock rows in red
for (int row = 2; row <= 4; row++)
{
    var stockCell = ws[$"E{row}"];
    if (stockCell.IntValue < 10)
        stockCell.Style.BackgroundColor = "#FF6B6B";
}

wb.SaveAs("FormattedInventory.xlsx");
Console.WriteLine("FormattedInventory.xlsx saved.");
$vbLabelText   $csharpLabel

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

C# Export List of Objects to Excel with IronXL: Image 3 - Formatted worksheet

How Do You Apply Conditional Formatting Programmatically?

IronXL supports conditional formatting rules that mirror Excel's built-in feature. You can define rules based on cell value thresholds, text matching, or date ranges. Once a rule is applied to a range, IronXL writes the corresponding XLSX format metadata so the file behaves exactly as expected when opened in Excel or Google Sheets.

This is particularly useful when the exported file will be viewed by non-technical stakeholders who expect color-coded reports rather than plain tabular data.

How Do You Sort and Filter Data Before Exporting?

You can sort and filter your List<T> before writing it to Excel. Using standard LINQ, you can order employees by department and salary, or filter products to active items only. Once the filtered list is ready, write it to the worksheet using the same column-by-column approach shown above.

IronXL also supports sorting cells within an already-populated range directly in the workbook -- allowing post-population sorts without returning to the original collection.

How Do You Export Lists to Other File Formats?

IronXL is not limited to XLSX. The same WorkBook object can be saved to several formats with a single method change:

  • XLSX -- Default modern Excel format: workbook.SaveAs("output.xlsx")
  • XLS -- Legacy Excel format for older Office versions
  • CSV -- Comma-separated values for data pipeline compatibility
  • TSV -- Tab-separated values

When exporting to CSV format, each worksheet becomes a separate CSV file. This makes IronXL useful not only for end-user reports but also for generating intermediate data files consumed by ETL pipelines, data science tools, or third-party APIs. For exporting DataGridView data -- a common pattern in Windows Forms apps -- IronXL slots in cleanly without requiring additional adapters.

How Do You Handle Large Data Sets Efficiently?

When exporting thousands of rows, performance becomes a concern. Keep the following guidelines in mind:

  • Populate a DataTable first and write rows in a loop rather than calling individual cell-setter methods repeatedly from reflection.
  • Call AutoSizeColumn only after all data is written, because it is a read-scan operation.
  • Avoid opening the workbook for re-reading and re-saving in a tight loop -- build the complete dataset in memory, then call SaveAs once.
  • For datasets over 100,000 rows, consider splitting the export across multiple worksheets to maintain Excel's row-count limits and keep file sizes manageable.

IronXL also provides an ASP.NET Core export workflow where the XLSX file is written directly to a MemoryStream and returned as a file download response, bypassing disk I/O entirely.

How Do You Export Lists to Excel in ASP.NET Core?

When building web APIs or Razor Pages applications, you typically want to return the Excel file as an HTTP response rather than saving it to disk. The pattern below returns a FileContentResult from a controller action:

The controller injects a service that builds the WorkBook, calls workbook.ToByteArray(), then returns the bytes with the MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and a Content-Disposition: attachment header. This approach works in any .NET 10 minimal API or MVC controller.

For a complete walkthrough, see the ASP.NET Core Excel export tutorial and the Blazor export tutorial if you are building a Blazor WebAssembly or Blazor Server application.

How Do You Get Started With IronXL Today?

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

You can also use IronXL to read and edit existing workbooks, export Excel data to DataTable for further processing, or create pivot tables for summary reporting. Pair any of these capabilities with the formatting options shown above to produce spreadsheets that require no manual adjustments before distribution.

IronXL is available on NuGet and works with any project targeting .NET 10, .NET 8, or .NET Framework 4.6.2+. The Open XML SDK underlies the XLSX file format that IronXL reads and writes, giving you confidence that generated files conform to the ECMA-376 standard and open correctly in any OOXML-compatible application.

Get stated with IronXL now.
green arrow pointer

Ready to start exporting C# lists to Excel? Download IronXL now and experience how quickly you can convert list objects to Excel in your .NET applications. For production deployments, explore the flexible licensing options that scale with your needs. Visit the documentation for more tutorials and examples.

Frequently Asked Questions

How can I export a C# list to an Excel file?

You can export a C# list to an Excel file using IronXL's ImportData method, which simplifies the process without requiring Office Interop.

Why should I use IronXL for exporting data to Excel?

IronXL provides a streamlined solution for exporting data to Excel by eliminating traditional complexities and offering easy integration with .NET, .NET Core, or the .NET Framework.

Do I need Microsoft Office installed to use IronXL?

No, IronXL does not require Microsoft Office to be installed. It operates independently, allowing you to create and manipulate Excel files programmatically.

Can IronXL handle complex objects in lists when exporting to Excel?

Yes, IronXL can handle both generic lists and complex objects, providing flexibility in exporting various types of data to Excel.

Is IronXL compatible with .NET Core?

Yes, IronXL is compatible with .NET Core, as well as .NET and the .NET Framework, making it versatile for different development environments.

What is the advantage of using IronXL's ImportData method?

The ImportData method in IronXL simplifies the process of transferring data from C# lists to Excel, reducing code complexity and improving productivity.

Can I create professional spreadsheets using IronXL?

Absolutely, IronXL allows developers to transform List objects into professional spreadsheets easily, suitable for reports, data sharing, or backups.

Are there code examples available for using IronXL?

Yes, the IronXL documentation and tutorials provide simple code examples for exporting both generic lists and complex objects to Excel.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me