How to Generate an Excel File in C# Using IronXL
Generating Excel worksheet files programmatically in C# or Visual Basic traditionally required Microsoft Office installation or complex COM Interop. IronXL changes this completely, offering a simple API that creates Excel application 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're creating reports, exporting data(XLS file or XLSX files), or automating spreadsheet generation, you'll learn the essential techniques for working with Excel in .NET applications.

Why Generate Excel Worksheet 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 8/9 applications.

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. Without any registry entries, any COM registration,and any Office service packs to maintain. Your continuous integration pipelines work seamlessly, 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 of working with several different XML files, giving you a much faster path to working with Excel programmatically.

How to Install IronXL in Your C# Project?
Installing IronXL takes just moments through NuGet Package Manager in Solution Explorer. In Visual Studio, right-click your project 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#.
Alternatively, use the Package Manager Console:
Install-Package IronXL.Excel

For .NET CLI users working with modern C# projects:
dotnet add package IronXL.Exceldotnet add package IronXL.ExcelVerify installation with this simple test to create Excel file programmatically:
using IronXL;
// new Excel workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");using IronXL;
// new Excel workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");IRON VB CONVERTER ERROR developers@ironsoftware.comThis code creates an in-memory workbook object. If it 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 documentation. Ready to get started? Download IronXL now and begin generating Excel files in minutes.
Output

How to 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 generate Excel files 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 some basic data
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 some basic data
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");IRON VB CONVERTER ERROR developers@ironsoftware.comThis 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 allows you to embed document information that appears in Excel's file properties, adhering to 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 worksheet management tutorial.
Output

How to 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.
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales"); // C2
worksheet.SetCellValue(2, 2, "Marketing"); // C3
// Array-based 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("FirstExcelFile.xlsx");WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales"); // C2
worksheet.SetCellValue(2, 2, "Marketing"); // C3
// Array-based 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("FirstExcelFile.xlsx");IRON VB CONVERTER ERROR developers@ironsoftware.comThe 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, perfect 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.
Output

For larger datasets, consider this pattern:
// Populate from a data source
var employees = GetEmployeeData(); // Your data source
for (int row = 0; row < employees.Count; row++)
{
worksheet[$"A{row + 2}"].Value = employees[row].Id;
worksheet[$"B{row + 2}"].Value = employees[row].Name;
worksheet[$"C{row + 2}"].Value = employees[row].Department;
worksheet[$"D{row + 2}"].Value = employees[row].Salary;
}// Populate from a data source
var employees = GetEmployeeData(); // Your data source
for (int row = 0; row < employees.Count; row++)
{
worksheet[$"A{row + 2}"].Value = employees[row].Id;
worksheet[$"B{row + 2}"].Value = employees[row].Name;
worksheet[$"C{row + 2}"].Value = employees[row].Department;
worksheet[$"D{row + 2}"].Value = employees[row].Salary;
}IRON VB CONVERTER ERROR developers@ironsoftware.comThis approach iterates through your data collection, mapping each property to its corresponding column. The string interpolation ($"A{row + 2}") dynamically generates cell addresses, starting from row 2 to preserve headers.
How to Apply Professional Formatting?
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 when you generate Excel files in C#.
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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 to 20 characters
// 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;
// To set border color, use:
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
dataRange.Style.LeftBorder.Color = "#000000";
dataRange.Style.RightBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability
for (int row = 2; row <= 3; row++)
{
if (row % 2 == 0)
{
worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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 to 20 characters
// 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;
// To set border color, use:
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
dataRange.Style.LeftBorder.Color = "#000000";
dataRange.Style.RightBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability
for (int row = 2; row <= 3; row++)
{
if (row % 2 == 0)
{
worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}IRON VB CONVERTER ERROR developers@ironsoftware.comThis formatting code creates a professional appearance that meets enterprise 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, these are all essential for creating Excel files that match corporate branding guidelines.
Column width adjustments prevent text truncation. AutoSizeColumn() automatically fits content, while SetColumnWidth() 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 Excel specifications.
Borders define data boundaries, improving readability. The BorderType enum offers various styles: thin, medium, thick, dotted, and dashed. Alignment options center headers and right-align numbers, following spreadsheet conventions. Alternating row colors, often referred to as "banded rows," help readers track information across wide data sets. Learn more about advanced formatting to create formatted Excel data in our cell styling guide.
Output

How to 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.
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
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];
// Row total formula
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";
budget["C9"].Formula = "=C3/C7*100";
budget["D9"].Formula = "=D3/D7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");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
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];
// Row total formula
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";
budget["C9"].Formula = "=C3/C7*100";
budget["D9"].Formula = "=D3/D7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");IRON VB CONVERTER ERROR developers@ironsoftware.comThis 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 row total formulas (=SUM(B{i + 2}:D{i + 2})) calculate quarterly totals for each category. String interpolation dynamically generates the correct cell references for each row. Monthly totals sum entire columns, while percentage calculations divide specific cells by totals.
The EvaluateAll() method processes all formulas, updating calculated values throughout the workbook. This ensures formulas display results when opened in Excel. Without evaluation, Excel would show the formulas until the user triggers recalculation.
Output

How to Export Data from Databases to Excel?
Real-world applications often export database data to Excel for reporting and analysis. IronXL streamlines this process with built-in DataTable support, eliminating the need for manual field mapping when generating Excel files from C# applications.
using System.Data;
using System.Data.SqlClient;
// Simulate database retrieval (replace with your 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));
// Sample data (normally from database)
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");
// Get data from database
DataTable salesData = GetSalesData();
// Method 1: Manual mapping with formatting
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);
}
// Format headers
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]);
}
// Add total column with formula
reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}
// Add total header and format
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency 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";
// Format date column
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";
// Add 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";
// Auto-fit columns
for (int col = 0; col <= 6; col++)
{
reportSheet.AutoSizeColumn(col);
}
// Evaluate formulas and save
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");using System.Data;
using System.Data.SqlClient;
// Simulate database retrieval (replace with your 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));
// Sample data (normally from database)
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");
// Get data from database
DataTable salesData = GetSalesData();
// Method 1: Manual mapping with formatting
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);
}
// Format headers
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]);
}
// Add total column with formula
reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}
// Add total header and format
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency 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";
// Format date column
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";
// Add 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";
// Auto-fit columns
for (int col = 0; col <= 6; col++)
{
reportSheet.AutoSizeColumn(col);
}
// Evaluate formulas and save
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");IRON VB CONVERTER ERROR developers@ironsoftware.comThis comprehensive example demonstrates a complete database-to-Excel workflow for generating Excel files in C #. The DataTable simulates database retrieval - in production, replace this with your 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 utilizes Excel formulas to count orders and sum revenue, ensuring that these values are updated if the data changes. Currency and date formatting follow business document standards, while auto-sizing columns ensures all content displays properly. For handling larger datasets, explore our performance optimization guide.
Output

Need to streamline your Excel reporting? Get a license to unlock IronXL's full potential for production deployments.
How to 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.
// Create a multi-sheet workbook
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics");
// 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";
inventorySheet["A3"].Value = "Product";
inventorySheet["B3"].Value = "Stock Level";
inventorySheet["C3"].Value = "Reorder Point";
inventorySheet["D3"].Value = "Status";
// Add inventory data with conditional 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];
// Status based on stock level
string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
inventorySheet[$"D{i + 4}"].Value = status;
// Color code status
if (status == "REORDER")
{
inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}
}
// Create summary sheet referencing other sheets
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");
summarySheet["A1"].Value = "Company Overview";
summarySheet["A3"].Value = "Metric";
summarySheet["B3"].Value = "Value";
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\")";
// Format all sheets consistently
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
// Format headers
sheet["A1"].Style.Font.Bold = true;
sheet["A1"].Style.Font.Height = 14;
var headerRow = sheet["A3:D3"];
headerRow.Style.Font.Bold = true;
headerRow.Style.SetBackgroundColor("#E7E6E6");
}
// Save multi-sheet workbook
companyReport.SaveAs("CompanyReport.xlsx");// Create a multi-sheet workbook
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics");
// 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";
inventorySheet["A3"].Value = "Product";
inventorySheet["B3"].Value = "Stock Level";
inventorySheet["C3"].Value = "Reorder Point";
inventorySheet["D3"].Value = "Status";
// Add inventory data with conditional 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];
// Status based on stock level
string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
inventorySheet[$"D{i + 4}"].Value = status;
// Color code status
if (status == "REORDER")
{
inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}
}
// Create summary sheet referencing other sheets
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");
summarySheet["A1"].Value = "Company Overview";
summarySheet["A3"].Value = "Metric";
summarySheet["B3"].Value = "Value";
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\")";
// Format all sheets consistently
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
// Format headers
sheet["A1"].Style.Font.Bold = true;
sheet["A1"].Style.Font.Height = 14;
var headerRow = sheet["A3:D3"];
headerRow.Style.Font.Bold = true;
headerRow.Style.SetBackgroundColor("#E7E6E6");
}
// Save multi-sheet workbook
companyReport.SaveAs("CompanyReport.xlsx");IRON VB CONVERTER ERROR developers@ironsoftware.comThis example creates a complete multi-sheet report. Each worksheet serves a specific purpose: sales data, inventory tracking, and HR metrics. The summary sheet consolidates key metrics using cross-sheet formulas. Notice the sheet reference syntax in formulas "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 easily navigate between different data views.
What Are the Best Practices for Excel Generation?
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. Instead of loading entire datasets into memory, process data in chunks:
// Process large datasets efficiently
public void ExportLargeDataset(string filename)
{
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 1;
// Process in 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(filename);
}// Process large datasets efficiently
public void ExportLargeDataset(string filename)
{
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 1;
// Process in 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(filename);
}IRON VB CONVERTER ERROR developers@ironsoftware.comError handling prevents application crashes and provides meaningful feedback when generating Excel files:
try
{
WorkBook workbook = WorkBook.Create();
// Excel generation code
workbook.SaveAs("output.xlsx");
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Excel generation failed: {ex.Message}");
// Implement appropriate recovery or notification
}try
{
WorkBook workbook = WorkBook.Create();
// Excel generation code
workbook.SaveAs("output.xlsx");
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Excel generation failed: {ex.Message}");
// Implement appropriate recovery or notification
}IRON VB CONVERTER ERROR developers@ironsoftware.comFor web applications, generate Excel files in memory and stream to users:
// ASP.NET Core example
public IActionResult DownloadExcel()
{
WorkBook workbook = GenerateReport();
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx");
}// ASP.NET Core example
public IActionResult DownloadExcel()
{
WorkBook workbook = GenerateReport();
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx");
}IRON VB CONVERTER ERROR developers@ironsoftware.comDeployment considerations ensure smooth production operations. 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 temporary file operations if needed. For additional deployment guidance, consult the deployment documentation.
Conclusion
IronXL transforms Excel file generation in C# from a complex challenge into straightforward coding. You've learned to create workbooks, populate cells, apply formatting, use formulas, and export database data - all without Microsoft Office dependencies. These techniques for generating Excel files programmatically work consistently across Windows, Linux, and cloud platforms.
Ready to implement Excel generation in your C# applications? Start your free trial or explore the comprehensive API documentation for advanced features. For production deployments, view licensing options that match your project requirements.








