Skip to footer content
USING IRONXL

How to Create Excel Spreadsheets in C# .NET Core Using IronXL

Generating Excel spreadsheets programmatically in ASP.NET Core opens up powerful automation possibilities -- from financial reporting and inventory tracking to exporting data and automated dashboards. In web application development, integrating .NET Core Excel spreadsheet generation enhances data accessibility and reporting, allowing users to interact with and extract valuable insights from complex datasets. With IronXL for .NET, developers can create Excel files without installing Microsoft Office or relying on Office Interop. This cross-platform library runs on Windows, Linux, and macOS, making it ideal for modern data-driven applications deployed to Azure or Docker containers.

This tutorial walks through creating .NET Core Excel spreadsheets with professional formatting, formulas, and multiple export options. Whether building ASP.NET Core web applications, console applications, or background services, these techniques apply across all .NET 10 applications. By the end, you will have working code for generating production-ready Excel files that integrate with existing projects in Visual Studio or any .NET development environment.


How Do You Install IronXL in a .NET Core Project?

Before creating spreadsheets, you need to add IronXL to your project. Open the NuGet Package Manager Console in Visual Studio and run one of these commands:

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

The first command works in the Visual Studio Package Manager Console. The second works in any terminal using the .NET CLI. Both install the same NuGet package and add IronXL to your project references automatically.

Once installation completes, IronXL is ready to use with a single using directive. The library does not require any additional configuration, runtime dependencies, or Microsoft Office installation. It works on any platform where .NET 10 runs -- Windows, Linux, macOS, or any cloud environment.

For detailed installation options, including manual DLL download, see the IronXL installation guide. Linux developers should also review the Linux deployment documentation for platform-specific guidance.

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL for .NET: Image 1 - Installation


How Do You Create an Excel Spreadsheet Without Office Dependencies?

Traditional Microsoft Excel automation requires MS Office installation and uses Office Interop, which does not work on Linux or in containerized environments. As discussed in Microsoft's documentation on Office Interop, Office Interop introduces deployment complexity and licensing concerns. IronXL for .NET eliminates these limitations by providing a pure .NET solution that processes Excel files natively with full support for modern spreadsheet capabilities.

The library supports .NET 8, .NET 9, and .NET 10, along with earlier .NET Core versions. It handles XLSX, XLS, CSV, and other spreadsheet formats without external dependencies. This makes it particularly valuable for server-side applications, microservices, and scenarios where installing Microsoft Office is not practical. Easy integration via NuGet means you can start writing Excel files within minutes:

using IronXL;

// Create a new workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add an Excel worksheet with a custom name
WorkSheet sheet = workbook.CreateWorkSheet("SalesReport");
// Set a cell value
sheet["A1"].Value = "Product Sales Summary";
// Save the generated Excel file
workbook.SaveAs("SalesReport.xlsx");
using IronXL;

// Create a new workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add an Excel worksheet with a custom name
WorkSheet sheet = workbook.CreateWorkSheet("SalesReport");
// Set a cell value
sheet["A1"].Value = "Product Sales Summary";
// Save the generated Excel file
workbook.SaveAs("SalesReport.xlsx");
$vbLabelText   $csharpLabel

The WorkBook.Create() method initializes a new Excel workbook, accepting an ExcelFileFormat parameter to specify XLSX (modern XML-based format introduced in Excel 2007) or XLS (legacy binary format). XLSX is recommended for most scenarios due to smaller file sizes and better compatibility with modern tools. The CreateWorkSheet() method adds named worksheets where Excel data lives -- each workbook can contain multiple individual sheets for organizing related data.

Cell values are set using bracket notation that mirrors Excel's addressing system -- sheet["A1"] targets cell A1 directly. This syntax supports both specific cells and ranges, making bulk operations straightforward for any spreadsheet project.

Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL for .NET: Image 2 - Excel Output


How Do You Add Worksheets and Populate Data Programmatically?

Real-world Excel spreadsheets contain structured data across multiple worksheets. IronXL provides flexible methods for organizing information and populating cells efficiently, whether working with manual data entry or automated data pipelines in data-driven applications.

using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("MonthlySales");

// Set column names as headers
sheet["A1"].Value = "Month";
sheet["B1"].Value = "Revenue";
sheet["C1"].Value = "Units Sold";

// Populate Excel data using a loop (mock sales data)
string[] months = { "January", "February", "March", "April", "May", "June" };
decimal[] revenue = { 45000.50m, 52000.75m, 48500.25m, 61000.00m, 58750.50m, 67200.25m };
int[] units = { 150, 175, 160, 200, 190, 220 };

for (int i = 0; i < months.Length; i++)
{
    int row = i + 2;
    sheet[$"A{row}"].Value = months[i];
    sheet[$"B{row}"].Value = revenue[i];
    sheet[$"C{row}"].Value = units[i];
}

// Set a range of cells to the same value across columns
sheet["D2:D7"].Value = "Active";
workbook.SaveAs("MonthlySales.xlsx");
using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("MonthlySales");

// Set column names as headers
sheet["A1"].Value = "Month";
sheet["B1"].Value = "Revenue";
sheet["C1"].Value = "Units Sold";

// Populate Excel data using a loop (mock sales data)
string[] months = { "January", "February", "March", "April", "May", "June" };
decimal[] revenue = { 45000.50m, 52000.75m, 48500.25m, 61000.00m, 58750.50m, 67200.25m };
int[] units = { 150, 175, 160, 200, 190, 220 };

for (int i = 0; i < months.Length; i++)
{
    int row = i + 2;
    sheet[$"A{row}"].Value = months[i];
    sheet[$"B{row}"].Value = revenue[i];
    sheet[$"C{row}"].Value = units[i];
}

// Set a range of cells to the same value across columns
sheet["D2:D7"].Value = "Active";
workbook.SaveAs("MonthlySales.xlsx");
$vbLabelText   $csharpLabel

String interpolation ($"A{row}") enables dynamic cell addressing within loops, making it straightforward to populate rows programmatically from any data source. The range syntax sheet["D2:D7"] applies values to multiple cells simultaneously -- useful for status columns, default values, or initializing data regions. IronXL automatically handles data type conversion, storing decimals as numeric values and string content as text while preserving appropriate Excel data types for the generated file.

Working With Multiple Worksheets

Creating multiple worksheets organizes related Excel data logically within a single workbook:

WorkSheet summarySheet = workbook.CreateWorkSheet("Summary");
WorkSheet detailSheet = workbook.CreateWorkSheet("Details");
WorkSheet archiveSheet = workbook.CreateWorkSheet("Archive");
WorkSheet summarySheet = workbook.CreateWorkSheet("Summary");
WorkSheet detailSheet = workbook.CreateWorkSheet("Details");
WorkSheet archiveSheet = workbook.CreateWorkSheet("Archive");
$vbLabelText   $csharpLabel

For applications requiring database integration, IronXL works with Entity Framework Core, Dapper, or raw ADO.NET. Data from DataTable objects can be exported directly to worksheets, simplifying reporting workflows and allowing users to share data across systems.

Learn more about managing worksheets and writing Excel files in the documentation. For reading an existing Excel file, see the Excel file loading tutorial.

Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL: Image 3 - Multiple Worksheets Output


How Do You Apply Professional Formatting and Styling?

Raw data becomes meaningful when properly formatted. IronXL supports background colors, fonts, borders, and number formats -- essential formatting capabilities that transform Excel spreadsheets into polished reports suitable for executive presentations or client deliverables.

using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("FormattedReport");

// Create headers with styling
sheet["A1"].Value = "Category";
sheet["B1"].Value = "Amount";
sheet["C1"].Value = "Date";

// Apply header formatting to the Excel sheet
sheet["A1:C1"].Style.SetBackgroundColor("#2E86AB");
sheet["A1:C1"].Style.Font.Bold = true;
sheet["A1:C1"].Style.Font.SetColor("#FFFFFF");

// Add sample data to specific cells
sheet["A2"].Value = "Software License";
sheet["B2"].Value = 1299.99m;
sheet["C2"].Value = DateTime.Now;

// Format currency and date columns
sheet["B2"].FormatString = "$#,##0.00";
sheet["C2"].FormatString = "yyyy-MM-dd";

// Add borders around the data range
var dataRange = sheet["A1:C2"];
dataRange.Style.BottomBorder.SetColor("#000000");
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
workbook.SaveAs("FormattedReport.xlsx");
using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("FormattedReport");

// Create headers with styling
sheet["A1"].Value = "Category";
sheet["B1"].Value = "Amount";
sheet["C1"].Value = "Date";

// Apply header formatting to the Excel sheet
sheet["A1:C1"].Style.SetBackgroundColor("#2E86AB");
sheet["A1:C1"].Style.Font.Bold = true;
sheet["A1:C1"].Style.Font.SetColor("#FFFFFF");

// Add sample data to specific cells
sheet["A2"].Value = "Software License";
sheet["B2"].Value = 1299.99m;
sheet["C2"].Value = DateTime.Now;

// Format currency and date columns
sheet["B2"].FormatString = "$#,##0.00";
sheet["C2"].FormatString = "yyyy-MM-dd";

// Add borders around the data range
var dataRange = sheet["A1:C2"];
dataRange.Style.BottomBorder.SetColor("#000000");
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
workbook.SaveAs("FormattedReport.xlsx");
$vbLabelText   $csharpLabel

The Style property exposes formatting options matching Microsoft Excel's capabilities. Background colors accept hex codes (with or without the # prefix), while FormatString applies number formats identical to Excel's custom formatting syntax -- the same patterns work in both environments. Border styling supports Thin, Medium, Thick, and Double types, allowing precise control over cell boundaries in your Excel worksheet.

Advanced Formatting Techniques

For Excel spreadsheets with extensive data, CreateFreezePane(0, 1) keeps headers visible while scrolling -- a subtle enhancement that significantly improves usability for large datasets. Print configuration through sheet.PrintSetup handles orientation, margins, and scaling for physical output.

Explore additional styling options in the cell formatting guide and border configuration tutorial. These tools give you complete control over every aspect of cell appearance.


How Do You Use Excel Formulas for Automatic Calculations?

Excel's calculation engine automates data analysis, and IronXL provides full support for formulas. Set formulas as strings using standard Excel syntax, and IronXL calculates results automatically when requested -- essential for reporting and financial analysis.

using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("BudgetCalculations");

// Add expense data to the Excel workbook
sheet["A1"].Value = "Expense";
sheet["B1"].Value = "Amount";
sheet["A2"].Value = "Rent";
sheet["B2"].Value = 2500;
sheet["A3"].Value = "Utilities";
sheet["B3"].Value = 350;
sheet["A4"].Value = "Supplies";
sheet["B4"].Value = 875;
sheet["A5"].Value = "Marketing";
sheet["B5"].Value = 1200;

// Add formulas for calculations
sheet["A7"].Value = "Total:";
sheet["B7"].Formula = "=SUM(B2:B5)";
sheet["A8"].Value = "Average:";
sheet["B8"].Formula = "=AVERAGE(B2:B5)";
sheet["A9"].Value = "Maximum:";
sheet["B9"].Formula = "=MAX(B2:B5)";
sheet["A10"].Value = "Count:";
sheet["B10"].Formula = "=COUNT(B2:B5)";

// Calculate all formulas
workbook.EvaluateAll();

// Access calculated values programmatically
decimal total = sheet["B7"].DecimalValue;
Console.WriteLine($"Calculated total: {total}");
workbook.SaveAs("BudgetCalculations.xlsx");
using IronXL;

WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workbook.CreateWorkSheet("BudgetCalculations");

// Add expense data to the Excel workbook
sheet["A1"].Value = "Expense";
sheet["B1"].Value = "Amount";
sheet["A2"].Value = "Rent";
sheet["B2"].Value = 2500;
sheet["A3"].Value = "Utilities";
sheet["B3"].Value = 350;
sheet["A4"].Value = "Supplies";
sheet["B4"].Value = 875;
sheet["A5"].Value = "Marketing";
sheet["B5"].Value = 1200;

// Add formulas for calculations
sheet["A7"].Value = "Total:";
sheet["B7"].Formula = "=SUM(B2:B5)";
sheet["A8"].Value = "Average:";
sheet["B8"].Formula = "=AVERAGE(B2:B5)";
sheet["A9"].Value = "Maximum:";
sheet["B9"].Formula = "=MAX(B2:B5)";
sheet["A10"].Value = "Count:";
sheet["B10"].Formula = "=COUNT(B2:B5)";

// Calculate all formulas
workbook.EvaluateAll();

// Access calculated values programmatically
decimal total = sheet["B7"].DecimalValue;
Console.WriteLine($"Calculated total: {total}");
workbook.SaveAs("BudgetCalculations.xlsx");
$vbLabelText   $csharpLabel

The Formula property accepts standard Excel formula syntax -- the same formulas that work in Microsoft Excel work here. After setting formulas, call EvaluateAll() to compute results. This step ensures calculated values are available immediately through typed properties like DecimalValue, IntValue, or StringValue. Without calling EvaluateAll(), formulas still save correctly and calculate when opened in Excel, but programmatic access to results requires evaluation first.

Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL: Image 4 - Excel Formula Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL: Image 5 - Console Output

IronXL supports over 150 Excel functions, including mathematical operations (SUM, AVERAGE, ROUND), statistical functions (COUNT, MAX, MIN, STDEV), text manipulation (CONCATENATE, LEFT, RIGHT), and logical operations (IF, AND, OR). See the formula editing guide for advanced scenarios, including cell references across worksheets.

Built-In Aggregation Methods

For simpler scenarios where formulas do not need to persist in the Excel file, IronXL provides built-in aggregation methods:

decimal sum = sheet["B2:B5"].Sum();
decimal avg = sheet["B2:B5"].Avg();
decimal max = sheet["B2:B5"].Max();
decimal sum = sheet["B2:B5"].Sum();
decimal avg = sheet["B2:B5"].Avg();
decimal max = sheet["B2:B5"].Max();
$vbLabelText   $csharpLabel

These methods offer a C#-native alternative when calculations do not need to appear as visible formulas in the spreadsheet. The object-oriented API keeps your code readable and type-safe without requiring string-based formula syntax.


How Do You Export Excel Files and Serve Them for Download?

IronXL supports multiple export formats to meet different integration requirements. Beyond standard Excel formats, spreadsheets can export to CSV for data interchange, JSON for web applications, or TSV for legacy system compatibility. This flexibility makes it easy to integrate Excel generation into any workflow.

using IronXL;

WorkBook workbook = WorkBook.Load("BudgetCalculations.xlsx");

// Export to different formats
workbook.SaveAs("output.xlsx");      // Modern Excel (Office 2007+)
workbook.SaveAs("output.xls");       // Legacy Excel (97-2003)
workbook.SaveAsCsv("output.csv");    // CSV for data import/export
workbook.SaveAsJson("output.json");  // JSON for web APIs
using IronXL;

WorkBook workbook = WorkBook.Load("BudgetCalculations.xlsx");

// Export to different formats
workbook.SaveAs("output.xlsx");      // Modern Excel (Office 2007+)
workbook.SaveAs("output.xls");       // Legacy Excel (97-2003)
workbook.SaveAsCsv("output.csv");    // CSV for data import/export
workbook.SaveAsJson("output.json");  // JSON for web APIs
$vbLabelText   $csharpLabel

Each format serves specific use cases. XLSX works best for preserving formatting and formulas when sharing with Excel users. CSV provides maximum compatibility for importing into databases, analytics tools, or other spreadsheet applications. JSON integrates naturally with JavaScript frontends and REST APIs.

Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL: Image 6 - Modern Excel Output

.NET Core Excel Spreadsheet: Create Professional Excel Worksheet Files in C# Using IronXL: Image 7 - JSON Output

Serving Excel Files in ASP.NET Core

For ASP.NET Core web applications, serving Excel files as downloadable responses requires just a few lines of code:

[HttpGet("download-report")]
public IActionResult DownloadReport()
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workbook.CreateWorkSheet("Report");
    sheet["A1"].Value = "Generated Report";
    sheet["A2"].Value = DateTime.Now;

    var stream = workbook.ToStream();
    return File(
        stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "Report.xlsx"
    );
}
[HttpGet("download-report")]
public IActionResult DownloadReport()
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet sheet = workbook.CreateWorkSheet("Report");
    sheet["A1"].Value = "Generated Report";
    sheet["A2"].Value = DateTime.Now;

    var stream = workbook.ToStream();
    return File(
        stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "Report.xlsx"
    );
}
$vbLabelText   $csharpLabel

The ToStream() method creates a MemoryStream containing the complete Excel file, which ASP.NET Core's File() method returns with the appropriate MIME type. This pattern works identically for MVC controllers, API controllers, and minimal APIs. The browser automatically triggers a file download with the specified filename, allowing users to save the generated Excel file locally.

For high-traffic applications, consider generating reports asynchronously and caching results when the underlying data does not change frequently -- this approach improves performance significantly. The format conversion documentation covers additional export scenarios, including password-protected files.


How Does IronXL Compare to Other .NET Excel Libraries?

Several libraries exist for .NET Excel manipulation, each with different strengths. The table below shows how they compare across the criteria that matter most for production applications:

Comparison of .NET Excel libraries for .NET Core development
Feature IronXL Open-Source Alternatives
Microsoft Office Installation Required No No
Technical Support Yes (24/5 engineering team) Community-based
Cross-Platform (.NET Core) Full support Varies by library
Formula Calculation Engine 150+ functions Limited or none
License Model Commercial with free trial Various open-source

IronXL excels in enterprise scenarios requiring reliable technical support, documentation, and consistent updates. The library handles edge cases gracefully -- corrupted files, complex formulas, and large datasets -- where open-source alternatives may struggle. For teams prioritizing development velocity and production reliability, IronXL's commercial backing provides peace of mind.

According to discussions on Stack Overflow, developers frequently cite API simplicity and documentation quality as deciding factors when choosing Excel libraries for their .NET Core projects. The .NET Foundation also emphasizes cross-platform deployment as a priority for modern .NET development, making Office-independent libraries essential for maintainable solutions.

For security-conscious teams: IronXL operates independently of Microsoft Office and avoids Office Interop, which minimizes the risk of external vulnerabilities. Built-in support for encryption and password protection allows you to safeguard generated Excel files, ensuring that only authorized users can access or edit critical worksheets and data. Review the IronXL licensing options to find the plan that fits your team.


How Do You Handle Performance at Scale?

When your application generates Excel files for many concurrent users or processes large datasets, performance planning becomes critical. IronXL handles large workbooks efficiently because it operates entirely in memory without spawning Office processes or COM objects. This architecture keeps CPU and memory overhead predictable.

Key Performance Strategies

For data-heavy reports, populate cells in bulk rather than one at a time. Writing to a range using the bracket notation sheet["A1:Z1000"] can be significantly faster than iterating through individual cells when setting uniform values. For heterogeneous data, use loops with string interpolation for dynamic cell addressing.

For ASP.NET Core endpoints that generate reports on demand, consider caching the resulting byte arrays or MemoryStream output using IMemoryCache or a distributed cache like Redis. When the underlying data does not change between requests, cached Excel files can be returned immediately without regeneration. This strategy is particularly effective for dashboard exports and scheduled reports.

Multi-threaded generation is safe with IronXL when each thread operates on its own WorkBook instance. Avoid sharing workbook or worksheet instances across threads without synchronization. For background job processing, libraries like Hangfire or Quartz.NET work alongside IronXL for scheduled report generation, allowing you to pre-generate files during off-peak hours.

For the largest datasets, consider splitting data across multiple worksheets rather than creating single sheets with tens of thousands of rows. The export DataTable documentation shows efficient patterns for bulk data transfer from ADO.NET sources. Additional code examples covering advanced scenarios like reading existing Excel files or working with password-protected workbooks are available in the complete API reference.


What Are Your Next Steps?

Creating .NET Core Excel spreadsheets with IronXL turns what was once a dependency-heavy task into a straightforward .NET operation. From basic cell manipulation to formula calculations and professional formatting, the library provides a complete toolkit for spreadsheet automation that runs anywhere .NET 10 runs -- Windows servers, Linux containers, or cloud platforms.

The cross-platform architecture ensures identical behavior across development machines and production environments, eliminating the "works on my machine" problems common with Office Interop solutions. Start with the NuGet installation command, create your first workbook, and build from there using the patterns shown throughout this guide.

Download a free 30-day trial to explore all features with no limitations, or view licensing options for production deployment. Browse the IronXL code examples to see additional scenarios in action, and consult the IronXL documentation hub for the complete API reference and advanced configuration guides.

Frequently Asked Questions

What are the benefits of using IronXL for Excel spreadsheet generation in .NET Core?

IronXL allows developers to create Excel files programmatically without needing Microsoft Office or Office Interop, offering cross-platform compatibility on Windows, Linux, and macOS. This makes it ideal for modern, data-driven applications.

Can IronXL be used in ASP.NET Core applications?

Yes, IronXL can be integrated into ASP.NET Core applications, enabling powerful automation possibilities such as financial reporting, inventory tracking, and data exporting.

Is it possible to generate Excel spreadsheets in web applications using IronXL?

Yes. IronXL supports Excel sheet generation and download functionality in web applications, improving user experience by allowing users to export and interact with complex data tables.

Does IronXL require Microsoft Office to be installed?

No, IronXL does not require Microsoft Office to be installed. It operates independently of Office Interop, simplifying deployment and integration.

How does IronXL enhance data accessibility in .NET Core applications?

IronXL enhances data accessibility by allowing developers to programmatically generate Excel spreadsheets, making it easier for users to interact with and extract insights from complex datasets.

Can IronXL be deployed in cloud environments like Azure?

Yes, IronXL can be deployed in cloud environments such as Azure and Docker containers, making it suitable for scalable, cloud-based applications.

Is IronXL compatible with macOS and Linux?

IronXL is fully compatible with macOS and Linux, providing a cross-platform solution for Excel spreadsheet generation in .NET applications.

What types of applications benefit from using IronXL?

Applications that require data-driven solutions, such as financial reporting, inventory management, and automated dashboards, benefit greatly from using IronXL for Excel spreadsheet generation.

How does IronXL improve user experience in web applications?

IronXL improves user experience by enabling the export of complex data tables into Excel spreadsheets, making data more accessible and portable for end-users.

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