Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • C
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. ASP.NET MVC
  4. Excel Export in Asp.Net MVC using XlWorkbook

Excel Export in Asp.Net MVC using XlWorkbook

Date- Jun 11,2022

Updated Jan 2026

9382

Free Download Pay & Download
XlWorkbook ClosedXml

What is XlWorkbook?

XlWorkbook is a powerful third-party library that simplifies the process of exporting data into Excel files in .NET applications. It offers a wide range of formatting options, enabling developers to create visually appealing spreadsheets with minimal effort. With ClosedXML, you can easily manipulate Excel files, including adding styles, formulas, and charts, making it an excellent choice for generating reports and data exports.

ClosedXML is built on top of the OpenXML SDK, which means it works with the modern Excel file formats (.xlsx) and provides a user-friendly API to interact with Excel files without needing to understand the complexities of the underlying OpenXML structure. This library is particularly useful when you need to export data from a database in a structured and organized manner.

Prerequisites

Before you start exporting data to Excel using XlWorkbook in your Asp.Net MVC application, ensure you have the following prerequisites:

  • Visual Studio installed on your machine.
  • An Asp.Net MVC project set up.
  • Basic knowledge of C# and MVC architecture.
  • ClosedXML NuGet package installed in your project.

Installing ClosedXML NuGet Package

To get started, you need to install the ClosedXML library via NuGet. This can be done easily through the NuGet Package Manager Console or the NuGet Package Manager UI in Visual Studio.

Install-Package ClosedXML

After the installation is complete, you can start using ClosedXML in your project by adding the necessary namespace in your controller:

using ClosedXML.Excel;

Exporting Excel Using XlWorkbook in Asp.Net MVC

Once you have the ClosedXML library set up, you can proceed to export data. For this example, we will create a simple action method in a controller that generates an Excel file from a DataTable. Below is the sample code for the Download action method:

public ActionResult Download() {
DataTable table = DummyDataTableSource();
using (XLWorkbook workbook = new XLWorkbook()) {
table.TableName = "Table 1"; // Giving table name is mandatory and must be unique
workbook.Worksheets.Add(table);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Dummy Excel Export.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream()) {
workbook.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
}
}
Response.Flush();
Response.End();
return View();
}

In this code, we create a DataTable and populate it with some dummy data using the DummyDataTableSource method. We then create an instance of XLWorkbook, add the DataTable as a worksheet, and set the appropriate response headers to trigger a download in the browser.

Creating a Sample DataTable

The DummyDataTableSource method generates a simple DataTable with some sample data. Here is the implementation:

private static DataTable DummyDataTableSource() {
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Number");
table.Columns.Add("Address");
table.Columns.Add("City");
for (int i = 0; i < 10; i++) {
DataRow dr = table.NewRow();
dr["Name"] = "Name " + i;
dr["Number"] = "Number " + i;
dr["Address"] = "Address " + i;
dr["City"] = "City " + i;
table.Rows.Add(dr);
}
return table;
}

This method creates a DataTable with four columns: Name, Number, Address, and City, and populates it with ten rows of sample data. You can modify this method to pull data from a database or any other source as needed.

Triggering the Download from the View

To trigger the download of the Excel file, you can create a button in your view that links to the Download action. Here’s how you can do it:

<a style="margin-top:10px" class="btn btn-primary" href="/Home/Download">Export to Excel</a>

When the user clicks this button, the browser will initiate a download of the generated Excel file. You can see the result in the image below:

Advanced Formatting Options

ClosedXML also allows you to apply various formatting options to your Excel sheets. For instance, you can set background colors, font styles, borders, and more. Here's an example of how to format the headers of your Excel sheet:

workbook.Worksheets.Add(table);
var headerRange = table.AsRange().FirstRow();
headerRange.Style.Font.Bold = true;
headerRange.Style.Fill.BackgroundColor = XLColor.LightGray;
headerRange.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

In this code, we are accessing the first row of the DataTable (which contains the headers) and applying formatting to make the text bold, change the background color to light gray, and center the text. You can explore more formatting options in the ClosedXML documentation.

Edge Cases & Gotchas

When working with Excel exports, there are a few edge cases and common pitfalls to be aware of:

  • Large Data Sets: Exporting very large datasets can lead to performance issues. It’s advisable to implement pagination or limit the amount of data being exported at once.
  • Excel File Size Limits: Excel files have size limits (e.g., 2GB for .xlsx). Make sure your exported data does not exceed this to avoid errors.
  • Data Types: Ensure that the data types in your DataTable are compatible with Excel. For example, dates should be in a recognized date format.
  • Unique Table Names: Each worksheet in an Excel file must have a unique name. If you try to add a worksheet with a name that already exists, it will throw an exception.

Performance & Best Practices

To ensure optimal performance when exporting data to Excel, consider the following best practices:

  • Use Memory Streams: As demonstrated in the example, using a MemoryStream for the output can improve performance by avoiding file system I/O.
  • Minimize Data Size: Only include necessary data in the export. Filter out any irrelevant columns or rows to reduce file size and processing time.
  • Asynchronous Processing: For large exports, consider using asynchronous methods to avoid blocking the main thread and improve user experience.
  • Error Handling: Implement robust error handling to catch and log any exceptions that occur during the export process.

Conclusion

Exporting data to Excel using XlWorkbook in Asp.Net MVC is a straightforward process that can greatly enhance your application's data handling capabilities. By following the steps outlined in this tutorial, you should be able to implement Excel exports with various formatting options effectively.

  • ClosedXML simplifies the process of exporting data to Excel.
  • Ensure you handle edge cases such as large data sets and unique worksheet names.
  • Apply best practices to optimize performance and user experience.
  • Explore advanced formatting options to improve the presentation of your exported data.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Linkedin Sign In using LinkedinLogin Nuget package in Asp-Net MVC
Apr 14, 2023
How to export view as pdf in Asp.Net Core
Jul 05, 2022
Linkedin Sign In using LinkedinLogin Nuget package in Asp-Net MVC
Jul 05, 2022
Download Files as Zip file in Asp.Net
May 21, 2023
Previous in ASP.NET MVC
Create and display SSRS Report in ASP.NET MVC
Next in ASP.NET MVC
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the …

Comments

Contents

🎯

Interview Prep

Ace your ASP.NET MVC interview with curated Q&As for all levels.

View ASP.NET MVC Interview Q&As

More in ASP.NET MVC

  • Implement Stripe Payment Gateway In ASP.NET 58622 views
  • Jquery Full Calender Integrated With ASP.NET 39533 views
  • Microsoft Outlook Add Appointment and Get Appointment using … 27466 views
  • How to implement JWT Token Authentication and Validate JWT T… 25165 views
  • Payumoney Integration With Asp.Net MVC 23112 views
View all ASP.NET MVC posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor