Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Export an Excel File using ClosedXML

0.00/5 (No votes)
20 Jun 2016 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here