Thursday, December 05, 2013

Free Export DataSet/DataTable/List<t> to Excel (without using or even having Excel installed)

Code Project - A free "Export to Excel" C# class, using OpenXML

It's amazing that even now, in 2013, there are so many developers still asking for help on how to write C# and VB.Net code, to export their data to Excel.

Even worse, a lot of them will stumble on articles suggesting that they should write their data to a comma-separated file, but to give the file an .xls extension.

So, today, I'm going to walkthrough how to use my C# "Export to Excel" class, which you can add to your C# WinForms / WPF / ASP.Net application, using one line of code.

Depending on whether your data is stored in a DataSet, DataTable or List<>, you simply need to call one of these three functions, and tell them what (Excel) filename you want to write to.

  • public static bool CreateExcelDocument<T>(List<T> list, string ExcelFilename
  • public static bool CreateExcelDocument(DataTable dt, string ExcelFilename
  • public static bool CreateExcelDocument(DataSet ds, string ExcelFilename)

...

And that's all you have to do. The CreateExcelDocument function will create a "real" Excel file for you.

For example, if you had a created a DataSet containing three DataTables called

  • Drivers
  • Vehicles,
  • Vehicle Owners,

..then here's what your Excel file would look like. The class would create one worksheet per DataTable, and each worksheet would contain the data from that DataTable.

image

...

Look, friends don't let friends use Office InterOp... (omg, especially for server/automated ops!). There are any number of options now available, many free or reasonably priced. Just... don't.... do... it...

No comments: