Skip to footer content
USING IRONXL

How to Generate Excel Files in C# Using IronXL

Generating Excel worksheet files programmatically in C# traditionally required Microsoft Office installation or complex COM Interop. IronXL changes this completely, offering a simple API that creates Excel files without any Office dependencies. This tutorial walks you through building Excel files in C# using IronXL, from basic spreadsheet creation to advanced formatting and database integration. Whether you are creating reports, exporting data (XLS or XLSX files), or automating spreadsheet generation, you will learn the essential techniques for working with Excel in .NET applications.

How to Generate Excel File in C# Using IronXL: Image 1 - IronXL

Why Generate Excel Files Without Microsoft Office?

Developing Excel generation features without Office dependencies solves critical deployment challenges. Server environments rarely have Microsoft Office installed due to licensing costs and resource overhead. Each Office installation requires significant disk space and memory, making it impractical for cloud deployments or containerized applications.

IronXL eliminates these constraints by operating independently. Your C# Excel file generation runs on Windows, Linux, macOS, Docker containers, or Azure App Services without modification. This cross-platform compatibility means you write once and deploy anywhere, whether targeting .NET Framework, .NET Core, or .NET 10 applications.

How to Generate Excel File in C# Using IronXL: Image 2 - Cross Platform

Performance improves dramatically without COM Interop overhead. Traditional Office automation creates separate process instances for each operation, consuming memory and CPU resources. IronXL processes everything in-memory within your application's process space, resulting in faster execution and lower resource consumption when you generate Excel files programmatically.

Deployment becomes straightforward since IronXL ships as a single NuGet package. No registry entries, no COM registration, and no Office service packs to maintain. Your continuous integration pipelines work without friction, and Docker containers remain lightweight. This simplified approach has made IronXL a popular choice, as discussed in various developer forums where professionals share their experiences with Excel automation.

Some developers still explore Microsoft's Open XML Productivity Tool for working directly with Office Open XML file structures. Still, that approach requires more manual effort and detailed knowledge of the XML schema and Open XML SDK installation. IronXL abstracts these complexities away, giving you a much faster path to working with Excel programmatically.

How to Generate Excel File in C# Using IronXL: Image 3 - Features

How Do You Install IronXL in a C# Project?

Installing IronXL takes just moments through NuGet Package Manager in Visual Studio. Right-click your project in Solution Explorer and select "Manage NuGet Packages." Search for "IronXL.Excel" and click Install. The package automatically includes all dependencies required for generating Excel files in C#.

To install via the Package Manager Console or the .NET CLI, use either of the following commands:

Install-Package IronXL.Excel
dotnet add package IronXL.Excel
Install-Package IronXL.Excel
dotnet add package IronXL.Excel
SHELL

How to Generate Excel File in C# Using IronXL: Image 4 - Installation

Verify the installation with this simple test to confirm the library is ready:

using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
$vbLabelText   $csharpLabel

If this runs without errors, IronXL is ready for use. The library supports all modern .NET versions, ensuring compatibility with your existing projects. For detailed installation guidance and troubleshooting, consult the official NuGet installation documentation.

Output

How to Generate Excel File in C# Using IronXL: Image 5 - Console Output

How Do You Create Your First Excel File?

Creating Excel files with IronXL starts with the WorkBook class, your gateway to all Excel operations. The library supports both modern XLSX and legacy XLS formats, giving you flexibility for different requirements when you create an Excel file in C#.

using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
$vbLabelText   $csharpLabel

This code demonstrates several key concepts for Excel file generation. The WorkBook.Create() method initializes a new Excel file in memory. You specify the format using the ExcelFileFormat enum -- choose XLSX for modern Excel compatibility or XLS for legacy support. The Metadata property lets you embed document information that appears in Excel's file properties, following Microsoft's document property standards.

The CreateWorkSheet() method adds a new sheet with the specified name. Excel's familiar cell notation (A1, B1, etc.) makes setting values intuitive. IronXL automatically handles data type conversion, recognizing dates, numbers, and text without explicit casting. The SaveAs() method writes the complete Excel file to disk. For more worksheet operations, explore the how to write Excel file guide.

Output

How to Generate Excel File in C# Using IronXL: Image 6 - Basic Excel Output

How Do You Write Data to Excel Cells?

IronXL provides multiple approaches for populating Excel cells, from individual cell assignment to bulk range operations. Understanding these methods helps you choose the most efficient approach for your data scenario when you write to an Excel file.

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
$vbLabelText   $csharpLabel

The code shows IronXL's flexible cell addressing. String notation ("A1") feels natural for Excel users, while numeric indices offer programmatic control for loops and dynamic generation. Range assignments ("B1:B3") efficiently set multiple cells to the same value, ideal for initializing columns or applying default values.

IronXL intelligently handles different data types. Decimals maintain precision for financial data, DateTime objects format correctly as Excel dates, and booleans appear as TRUE/FALSE. This automatic conversion eliminates manual formatting code while ensuring data integrity. For large datasets, explore the import data guide for additional patterns.

Output

How to Generate Excel File in C# Using IronXL: Image 7 - Excel Output

How Do You Apply Professional Formatting to Excel Files?

Professional Excel files require more than raw data. IronXL's styling API transforms plain spreadsheets into polished business documents through formatting, colors, and visual hierarchy. You can apply cell formatting to control every visual aspect of your spreadsheet.

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
$vbLabelText   $csharpLabel

This formatting code creates a professional appearance that meets business standards. Bold headers with background colors establish visual hierarchy. The SetBackgroundColor() method accepts hex color codes, giving precise control over your color scheme. Font properties include size, color, bold, italic, and underline options -- all essential for creating Excel files that match corporate branding guidelines.

Column width adjustments prevent text truncation. AutoSizeColumn() automatically fits content, while GetColumn().Width provides exact control. Number formatting uses Excel's format codes -- for example, "$#,##0.00" displays currency with thousand separators and two decimal places. Date formatting follows similar patterns, using standard Excel date format strings as documented in Microsoft's number format codes reference.

Borders define data boundaries, improving readability. The BorderType enum offers various styles: thin, medium, thick, dotted, and dashed. Alternating row colors, often referred to as "banded rows," help readers track information across wide data sets. To learn more about merging cells and other layout features, see the merge cells guide.

Output

How to Generate Excel File in C# Using IronXL: Image 8 - Formatted Excel Output

How Do You Use Excel Formulas Programmatically?

Excel formulas bring spreadsheets to life with automatic calculations. IronXL supports formula creation and evaluation, enabling dynamic spreadsheets that update automatically.

using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
$vbLabelText   $csharpLabel

This budget example illustrates the practical application of formulas. The Formula property accepts standard Excel formula syntax, starting with an equals sign. IronXL supports common functions: SUM, AVERAGE, COUNT, MAX, MIN, and many others. Cell references in formulas work exactly as in Excel, including relative and absolute references.

The EvaluateAll() method processes all formulas, updating calculated values throughout the workbook. This ensures formulas display results when the file is opened in Excel. Without evaluation, Excel would show the formula text until the user triggers recalculation. For more on reading formula results, see the read Excel file documentation.

Output

How to Generate Excel File in C# Using IronXL: Image 9 - Excel Output using Formulas

How Do You Export Database Data to Excel?

Real-world applications often export database data to Excel for reporting and analysis. IronXL makes this process straightforward with built-in DataTable support, eliminating the need for manual field mapping when exporting Excel from C# applications.

using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
$vbLabelText   $csharpLabel

This example demonstrates a complete database-to-Excel workflow. The DataTable simulates database retrieval -- in production, replace this with actual database queries using Entity Framework, Dapper, or ADO.NET. The manual mapping approach gives complete control over formatting and layout, as recommended by Microsoft's data export best practices.

The code creates a professional report with a title, formatted headers, and data rows. Formula columns calculate line totals dynamically. The summary section uses Excel formulas to count orders and sum revenue, ensuring that these values update if the data changes. For working with DataSets and larger data structures, see the Excel to DataSet conversion guide.

Output

How to Generate Excel File in C# Using IronXL: Image 10 - Database Export to Excel Output

Need to put Excel reporting into production? Get a license to unlock IronXL's full potential for production deployments.

How Do You Handle Multiple Worksheets?

Complex Excel files often require multiple worksheets to organize related data. IronXL simplifies multi-sheet management with intuitive methods for creating, accessing, and organizing worksheets. You can open and manage workbook sheets with just a few lines of code.

using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
$vbLabelText   $csharpLabel

This example creates a complete multi-sheet report. Each worksheet serves a specific purpose: sales data, inventory tracking, and a summary view. The summary sheet consolidates key metrics using cross-sheet formulas. Notice the sheet reference syntax -- "Sales!B4:B7" refers to cells B4 through B7 on the Sales sheet.

The inventory sheet demonstrates conditional logic, coloring low-stock items red for immediate attention. The foreach loop applies consistent formatting across all sheets, maintaining a professional appearance throughout the workbook. Sheet names appear as tabs in Excel, allowing users to navigate between different data views easily.

What Are the Best Practices for Excel File Generation in C#?

Efficient Excel file generation in C# requires thoughtful approaches to memory usage, error handling, and deployment. These practices ensure your applications scale effectively while maintaining reliability when creating Excel spreadsheets programmatically.

Memory management becomes critical with large files. Process data in batches rather than loading entire datasets at once. The following pattern keeps memory usage predictable for high-volume exports:

using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
$vbLabelText   $csharpLabel

For web applications, generate Excel files in memory and stream directly to users rather than writing temporary files to disk. Always wrap generation logic in error handling to prevent crashes and provide meaningful feedback:

// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
$vbLabelText   $csharpLabel

The table below summarizes key best practices and when to apply them:

IronXL Best Practices for Excel Generation in C#
Scenario Recommended Approach Benefit
Large datasets (>10,000 rows) Batch processing with chunked writes Reduced memory footprint
Web application downloads MemoryStream instead of temp files No disk IO, faster response
Production deployment Include valid IronXL license key No watermark on generated files
Currency and dates Use FormatString property Correct locale display in Excel
Dynamic reports Call EvaluateAll() before SaveAs() Formulas show computed values

IronXL works in restricted environments without elevated permissions, making it suitable for shared hosting and containerized deployments. Include the IronXL license file in your deployment package, and ensure your application has write permissions for any temporary file operations needed. For additional deployment guidance, consult the IronXL features overview and the full API documentation.

Where Can You Go From Here?

IronXL transforms Excel file generation in C# from a complex challenge into straightforward coding. You have learned to create workbooks, populate cells, apply formatting, use formulas, export database data, and manage multiple worksheets -- all without Microsoft Office dependencies. These techniques work consistently across Windows, Linux, and cloud platforms targeting .NET 10.

To go deeper, explore the IronXL how-to guides for reading and modifying existing Excel files, or the trial license page to get started in production. View licensing options that match your project requirements and scale.

How to Generate Excel File in C# Using IronXL: Image 11 - Licensing

Frequently Asked Questions

How can I generate Excel files using C#?

You can generate Excel files in C# by using IronXL, which provides a simple API for creating Excel files without requiring Microsoft Office installation or complex COM Interop.

Is Microsoft Office required to work with Excel files in C#?

No, Microsoft Office is not required. IronXL allows you to create and manipulate Excel files in C# without any Office dependencies.

What are the advantages of using IronXL over traditional methods?

IronXL simplifies the process of generating Excel files by eliminating the need for Microsoft Office and complex COM Interop, offering a straightforward API for Excel file creation and manipulation.

Can I integrate databases with Excel files using IronXL?

Yes, IronXL supports advanced operations such as database integration, allowing you to export data to Excel files efficiently.

What file formats can be generated with IronXL?

IronXL allows you to create both XLS and XLSX file formats, making it versatile for different Excel file generation needs.

Does IronXL support advanced formatting in Excel files?

Yes, IronXL supports advanced formatting features, enabling you to customize the appearance and structure of your Excel files.

Is it possible to automate spreadsheet generation using IronXL?

Yes, IronXL provides tools and techniques to automate the generation of spreadsheets, streamlining processes like report creation and data export.

How can I create reports using Excel in .NET applications?

IronXL offers an easy way to create reports by generating Excel files directly within .NET applications, providing a powerful solution for data presentation.

What techniques are essential for working with Excel in C#?

Essential techniques for working with Excel in C# using IronXL include basic spreadsheet creation, advanced formatting, and database integration.

Where can I find documentation for using IronXL in C#?

You can find comprehensive documentation for using IronXL in C# on the Iron Software website, which includes tutorials and examples for various use cases.

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