How to Generate Excel Report in ASP.NET C#

Cody Schneider8 min read

So, you need to export data from your ASP.NET C# application into an Excel spreadsheet. This is one of the most common feature requests in web development, letting business users slice, dice, and analyze application data in their favorite tool. This tutorial will walk you through the most effective and professional way to generate Excel reports in C#, using a modern ASP.NET Core application as our example.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

We'll cover the best libraries for the job, provide step-by-step code examples, and share some best practices to help you avoid common pitfalls. Let’s get your C# code creating beautiful, functional Excel files.

Why Is Exporting to Excel Still So Popular?

In a world of interactive dashboards and real-time analytics, you might wonder why the "Export to Excel" button is still a fixture in so many apps. The answer is simple: business users live in spreadsheets.

  • Familiarity: Nearly everyone in a business role knows their way around Excel. It's the universal language for ad-hoc data analysis.
  • Flexibility: Once the data is in Excel, users can create their own pivot tables, charts, and formulas without asking for new development features.
  • Offline Access & Sharing: Spreadsheets are portable. They can be easily emailed, shared, and analyzed without needing to be logged into your application.

Providing an Excel export is less about creating a primary reporting tool and more about empowering your non-technical users to work with data in a way that’s comfortable for them.

Methods for Generating Excel Reports in C#

When you need to create an Excel file from your C# code, you have a few options. Let's break them down from the simplest to the most powerful.

1. The Simple CSV Approach

A CSV (Comma-Separated Values) file is a plain text file that can be opened by Excel. Generating one is incredibly simple - you just need to create a string with your data, using commas to separate columns and new lines to separate rows.

  • Pros: Extremely easy and fast to generate. No external libraries are needed.
  • Cons: No formatting whatsoever. You can't have bold headers, text colors, cell formatting (like currency), formulas, or multiple sheets. Data type issues can also crop up if Excel auto-formats numbers incorrectly.

2. Third-Party Libraries (The Best Way)

This is the recommended approach for any professional application. Third-party libraries give you full control over the Excel file format (.xlsx), allowing you to create rich, formatted reports with formulas, charts, images, and multiple worksheets. They do the heavy lifting of building the complex XML structure of a modern Excel file.

  • Pros: Full control over formatting, formulas, and advanced features. They are self-contained and don't require Excel to be installed on your server.
  • Cons: You need to add a NuGet package and learn the library's specific API (which is what this tutorial is for!).

Some of the most popular libraries include EPPlus, ClosedXML, and NPOI. We'll be focusing on EPPlus in our step-by-step guide.

3. Using Office Interop (Please Don't Do This on a Server)

It's technically possible to automate the actual Excel application on your server using Microsoft.Office.Interop.Excel. This involves programmatically opening Excel, creating a workbook, filling cells, and saving the file - just like a user would, but in code.

  • Pros: You can theoretically do anything the Excel application can do.
  • Cons: This is a server-side nightmare. It requires Microsoft Office to be installed on your web server, which is often against licensing terms and is a security risk. It's slow, not scalable, and notoriously unstable in a multi-threaded server environment. For web applications, avoid this method at all costs.
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step-by-Step Guide: Generate an Excel Report with EPPlus in ASP.NET Core

Let's build a feature that generates a sales report. We'll use EPPlus because it's powerful, feature-rich, and very well-documented. Note that as of version 5, EPPlus uses the Polyform Noncommercial license - meaning it's free for non-commercial use but requires a commercial license for business use. Version 4.x under the LGPL license is still available if you have licensing constraints.

Step 1: Set Up Your ASP.NET Core Project

First, create a standard ASP.NET Core MVC project in Visual Studio. Once your project is ready, we need to install the EPPlus NuGet package.

You can do this using the NuGet Package Manager Console: Install-Package EPPlus

Step 2: Prepare Your Data Models and Services

For our example, let's assume we have a simple SalesRecord model and a service that returns a list of these records. This mimics fetching data from a database.

The SalesRecord Model:

public class SalesRecord
{
    public int OrderId { get, set, }
    public string Region { get, set, }
    public string Product { get, set, }
    public int Quantity { get, set, }
    public decimal UnitPrice { get, set, }
    public decimal TotalPrice => Quantity * UnitPrice,
}

A simple service to generate dummy data:

public class SalesDataService
{
    public List<SalesRecord> GetSalesRecords()
    {
        // In a real app, this would come from a database
        return new List<SalesRecord>
        {
            new SalesRecord { OrderId = 101, Region = "North", Product = "Widget A", Quantity = 5, UnitPrice = 10.00m },
            new SalesRecord { OrderId = 102, Region = "South", Product = "Widget B", Quantity = 8, UnitPrice = 15.50m },
            new SalesRecord { OrderId = 103, Region = "North", Product = "Widget C", Quantity = 3, UnitPrice = 25.00m },
            new SalesRecord { OrderId = 104, Region = "East",  Product = "Widget A", Quantity = 12, UnitPrice = 10.00m },
            new SalesRecord { OrderId = 105, Region = "South", Product = "Widget B", Quantity = 2, UnitPrice = 15.50m },
            new SalesRecord { OrderId = 106, Region = "West",  Product = "Widget C", Quantity = 7, UnitPrice = 25.00m }
        },
    }
}
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step 3: Create the Controller Action to Generate the Report

Now for the main event. In your controller (e.g., ReportsController.cs), we'll create an action method called ExportSalesData that generates and returns the Excel file.

Here’s the complete C# code for the controller action:

using Microsoft.AspNetCore.Mvc,
using OfficeOpenXml, // From EPPlus
using OfficeOpenXml.Style, // From EPPlus
using System.Drawing, // Required for color

public class ReportsController : Controller
{
    private readonly SalesDataService _salesDataService,

    public ReportsController()
    {
        _salesDataService = new SalesDataService(),
        //Set EPPlus license context
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial,
    }

    public IActionResult ExportSalesData()
    {
        var salesData = _salesDataService.GetSalesRecords(),
        byte[] fileContents,

        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Sales Report"),

            // --- 1. Add headers ---
            worksheet.Cells[1, 1].Value = "OrderID",
            worksheet.Cells[1, 2].Value = "Region",
            worksheet.Cells[1, 3].Value = "Product",
            worksheet.Cells[1, 4].Value = "Quantity",
            worksheet.Cells[1, 5].Value = "Unit Price",
            worksheet.Cells[1, 6].Value = "Total Price",

            // --- 2. Style headers ---
            using (var range = worksheet.Cells["A1:F1"])
            {
                range.Style.Font.Bold = true,
                range.Style.Fill.PatternType = ExcelFillStyle.Solid,
                range.Style.Fill.BackgroundColor.SetColor(Color.LightGray),
                range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center,
            }

            // --- 3. Add data ---
            int row = 2,
            foreach (var record in salesData)
            {
                worksheet.Cells[row, 1].Value = record.OrderId,
                worksheet.Cells[row, 2].Value = record.Region,
                worksheet.Cells[row, 3].Value = record.Product,
                worksheet.Cells[row, 4].Value = record.Quantity,
                worksheet.Cells[row, 5].Value = record.UnitPrice,
                worksheet.Cells[row, 6].Value = record.TotalPrice,
                row++,
            }

            // --- 4. Format columns ---
            worksheet.Cells["E:E"].Style.Numberformat.Format = "$#,##0.00",
            worksheet.Cells["F:F"].Style.Numberformat.Format = "$#,##0.00",

            // --- 5. Add a formula for a total ---
            int lastRow = salesData.Count + 1,
            worksheet.Cells[lastRow + 1, 5].Value = "Grand Total:",
            worksheet.Cells[lastRow + 1, 6].Formula = $"SUM(F2:F{lastRow})",
            worksheet.Cells[lastRow + 1, 5].Style.Font.Bold = true,
            worksheet.Cells[lastRow + 1, 6].Style.Font.Bold = true,

            // --- 6. Autofit columns for readability ---
            worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(),

            fileContents = package.GetAsByteArray(),
        }

        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        string fileName = $"SalesReport_{DateTime.Now:yyyyMMddHHmmss}.xlsx",
        return File(fileContents, contentType, fileName),
    }
}
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Step 4: Create a Link to Download the Report

Finally, in your view (e.g., Views/Home/Index.cshtml), add a simple link that points to your new controller action:

<a class="btn btn-primary" asp-controller="Reports" asp-action="ExportSalesData">Download Sales Report</a>

When a user clicks this link, their browser will prompt them to download a professionally formatted Excel file named SalesReport_...xlsx containing your application's data.

Best Practices and Quick Tips

  • Handle Large Datasets: If you're exporting thousands of rows, generating the file in memory can consume a lot of server RAM. For huge reports, consider creating the file in a temporary location on disk or using a background job to generate and email the report to the user. This prevents request timeouts and keeps your app responsive.
  • Asynchronous Operations: If your data retrieval (_salesDataService.GetSalesRecords()) is an async database call, make your controller action async by changing its signature to public async Task<IActionResult> ExportSalesData() and awaiting the data call.
  • Don't Forget Templates: For complex or ornately formatted reports, you can embed an existing Excel file as a template within your project. Load it with EPPlus, fill in the data cells, and then save it as a new file. This separates your C# logic from your report's design.
  • Choosing the Right Library:

Final Thoughts

Creating Excel reports in ASP.NET C# is a straightforward process when you use a dedicated library like EPPlus. By avoiding fragile methods like string-based CSVs or dependency-heavy Office Interop, you can build a robust, scalable exporting feature that provides immense value to your business users, allowing them to engage with your application's data in the format they know and love.

Manually creating C# code to generate exports is often a necessary step, but it’s part of a larger, often repeating cycle of manual reporting. After providing one export, users inevitably ask for another variation, and then another. We built an AI data analyst, Graphed, to streamline this entire process. Instead of writing code for each report, we let your team securely connect their data sources (from app databases to marketing platforms like Google Analytics or your CRM) and simply ask for what they need in plain English. This builds live, interactive dashboards automatically, freeing up developer time to focus on building features, not custom reports.

Related Articles

How to Enable Data Analysis in Excel

Enable Excel's hidden data analysis tools with our step-by-step guide. Uncover trends, make forecasts, and turn raw numbers into actionable insights today!