Export an Excel file using ClosedXML

5.00 avg. rating (97% score) - 1 vote

Introduciton

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 tool, which wil very minimal lines of code 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 fron 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!

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

We are using this method, so as to return a stream inorder to download the file in response using the stream. The save as method of the Closed XMl, helps create the stream.
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 codes 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.

Share on FacebookShare on Google+Share on LinkedInTweet about this on TwitterEmail this to someone
  • Narsapur Kumar

    how can i save the file in specific folder(ex..c;testfilename.xlsxl) ,insted of saving it in download folder

    • Алексей «HostelPlayer» Сергеев

      i think you need just change folderPath var. to whatever you need.
      p.s. sry for my inglish

  • Jeeva j

    How can I add watermark to the XL filestream.