Click here to Skip to main content
15,888,297 members
Articles / Productivity Apps and Services / Microsoft Office / Microsoft Excel
Tip/Trick

Export an Excel File using ClosedXML

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
20 Jun 2016CPOL1 min read 99.8K   9   11
How to export and Excel file using ClosedXML

Introduction

In today's tech world, most of the applications being developed under Logistics, Inventory, Internal Transaction and other domains require day-to-day data in Excel files and prefer Excel file operations in their applications.
I will be sharing one of the Nuget Package tools, which will be very minimal lines of code that will export an Excel file for us.

The tool is Closed XML.

1

Just write a few lines of code and done! It is developer friendly. If we have used the Open XML, there are a lot of lines of code which are required to export an Excel from data. We can create Excel file of 2007/2010 configuration without even Excel application.

To add the closed XML package, we add directly through the user interface, from the Nuget Gallery and also, we can use the Package Manager console to add the package using the below command:

PM> Install-Package ClosedXML

Snippet!

VB.NET
DataTable dt = new DataTable();
          dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
          new DataColumn("Name", typeof(string)),
          new DataColumn("Country",typeof(string)) });
          dt.Rows.Add(1, "C Sharp corner", "United States");
          dt.Rows.Add(2, "Suraj", "India");
          dt.Rows.Add(3, "Test User", "France");
          dt.Rows.Add(4, "Developer", "Russia");
          //Exporting to Excel
          string folderPath = "C:\\Excel\\";
          if (!Directory.Exists(folderPath))
          {
              Directory.CreateDirectory(folderPath);
          }
          //Codes for the Closed XML
          using (XLWorkbook wb = new XLWorkbook())
          {
              wb.Worksheets.Add(dt, "Customers");

              //wb.SaveAs(folderPath + "DataGridViewExport.xlsx");
              string myName = Server.UrlEncode("Test" + "_" +
              DateTime.Now.ToShortDateString() + ".xlsx");
              MemoryStream stream = GetStream(wb);// The method is defined below
              Response.Clear();
              Response.Buffer = true;
              Response.AddHeader("content-disposition",
              "attachment; filename=" + myName);
              Response.ContentType = "application/vnd.ms-excel";
              Response.BinaryWrite(stream.ToArray());
              Response.End();
          }

The above code instantiates a data table, with few data initialization.

VB.NET
public MemoryStream GetStream(XLWorkbook excelWorkbook)
        {
            MemoryStream fs = new MemoryStream();
            excelWorkbook.SaveAs(fs);
            fs.Position = 0;
            return fs;
        }

We are using this method, so as to return a stream in order to download the file in response using the stream. The save as method of the Closed XML, helps create the stream.

The downloaded file looks like below:

2

Conclusion

Here, I have shared the code where hard coded values are added, this is not the case everytime. We can always use the records from the database and create them as a datatable and then use the Closed XML. This really reduces a lot of code which is used in Open XML package. So, developers try it!! I will be sharing another article where I would show how to Import the same exported Excel file using Bulk copy using SQL Bulk copy.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMy 10000 thanks to you. Pin
Ashok Login23-Mar-22 1:56
Ashok Login23-Mar-22 1:56 
QuestionResponse is undefined Pin
vikasvanvi15-Feb-18 19:07
vikasvanvi15-Feb-18 19:07 
AnswerRe: Response is undefined Pin
Ersin Kecis5-Dec-18 20:36
professionalErsin Kecis5-Dec-18 20:36 
Questionexcelente Pin
Member 135022263-Nov-17 11:45
Member 135022263-Nov-17 11:45 
Questioncan you use closedxml with excel template Pin
Member 1268658723-Sep-17 19:08
Member 1268658723-Sep-17 19:08 
QuestionGetting timeout error with large data Pin
arunsinghdeveloper2-Jul-17 21:38
arunsinghdeveloper2-Jul-17 21:38 
QuestionIts really great, thank you Pin
praveen_adb22-Jun-16 3:55
praveen_adb22-Jun-16 3:55 
QuestionOpen XLS without saving Pin
sterenas21-Jun-16 7:15
sterenas21-Jun-16 7:15 
QuestionClosedxml Pin
Nathan Going20-Jun-16 19:08
Nathan Going20-Jun-16 19:08 
AnswerRe: Closedxml Pin
Passion4Code20-Jun-16 22:43
professionalPassion4Code20-Jun-16 22:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.