Creating an Excel file in C# is not as hard as many beginners believe. With no internal library support for creating Excel sheets, you are left with 3rd party libraries. Thankfully, there are plenty of free 3rd party libraries that help make it easy to create .XLS and .XLSX files.
Let’s get started with the tutorial. Before we get into the code, we need to go through the library options available when creating an Excel sheet. You can use EPPlus, a C# library for creating advanced Excel spreadsheets on the server, or you can use ExcelLibrary which can get your work done without much difficulty.
For the sake of simplicity, we will be using ExcelLibrary. However, if you need more control over your Excel sheet, it is advisable to use EEPlus which is frequently updated and comes under the GNU public license(GPL)
Alright, enough theory! Let’s get to the code below.
//Table and Dataset creation
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Creating locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Creating DB connection with OleDb.
OleDbConnection con = new OleDbConnection(dbConnectionString);
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
// DataSet used in table creation.s
Let’s go through the code to understand how it works. Most of it is self-explanatory and can be understood by the comments included within the code. The last line is what we all care about.
The library lets you create an Excel file with the help of the data set. Yup, it is that easy. For more features and functionalities, you need to visit the library page and look at its documentation.
Has anything to add to the tutorial series? Comment below and let us know.
You can also check on our website videos about C#. Below are some examples:
- Steam/C# gamedev: customizing game server (part 2) – C#
- C# compiler – new feature (part 33) – C#
You can also follow some of our broadcasters who program in C#, as below:
Another cool way to find out interesting things about C# is to access our project page!