Click here to Skip to main content
13,352,122 members (78,134 online)
Click here to Skip to main content
Add your own
alternative version


54 bookmarked
Posted 19 Jun 2012

Export DataTable to Excel with Formatting in C#

Rate this:
Please Sign up or sign in to vote.
Export a DataTable to an Excel file and add format to the contents while writing the Excel file.


In this tip, let us see how to export a DataTable to an Excel file and add format to the contents while writing the Excel file.

Step 1: Create a web application and add a class Student with properties as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;

namespace ExportToExcelFromDataTable
    public partial class _Default : System.Web.UI.Page
       protected void Page_Load(object sender, EventArgs e)
    public class Student
        public string Name { get; set; }
        public int StudentId { get; set; }
        public int Age { get; set; }

Step 2: I have added Gridview_Result. Create a list for students in the page_load event. Add a property dt of type DataTable. Bind the DataTable to the GridView after converting the List to a DataTable. The conversion class is described in the next step.

protected void Page_Load(object sender, EventArgs e)
    List<Student> Students = new List<Student>(){
        new Student() { Name = "Jack", Age = 15, StudentId = 100 },
        new Student() { Name = "Smith", Age = 15, StudentId = 101 },           
        new Student() { Name = "Smit", Age = 15, StudentId = 102 }
    ListtoDataTableConverter converter = new ListtoDataTableConverter();
    dt = converter.ToDataTable(Students);
    GridView_Result.DataSource = Students;

Step 3: Now we are going to convert this List object to a DataTable. For that we need to create a new class and a conversion method as below.

public class ListtoDataTableConverter
    public DataTable ToDataTable<T>(List<T> items)
        DataTable dataTable = new DataTable(typeof(T).Name);
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
            //Setting column names as Property names

         foreach (T item in items)
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);


         //put a breakpoint here and check datatable
        return dataTable;

The above method will set the property name as a column name for the DataTable and for each object in the list; it will create a new row in the DataTable and insert values. 

Step 4: I have written the below method which will convert a DataTable to an Excel file. In this method, I added font, made headers bold, and added a border. You can customize the method as per your needs.

private void ExporttoExcel(DataTable table)
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");
    HttpContext.Current.Response.Charset = "utf-8";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
      //sets font
    HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
    //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
    HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " + 
      "borderColor='#000000' cellSpacing='0' cellPadding='0' " + 
      "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
    //am getting my grid's column headers
    int columnscount = GridView_Result.Columns.Count;

    for (int j = 0; j < columnscount; j++)
    {      //write in new column
        //Get column headers  and make it as bold in excel columns
    foreach (DataRow row in table.Rows)
    {//write in new row
        for (int i = 0; i < table.Columns.Count; i++)


Step 4: Add a button and in the button click event, call the above method by passing a parameter.

protected void Btn_Export_Click(object sender, EventArgs e)

For the complete source code, please find the attached solution.


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


About the Author

Santhosh Kumar Jayaraman
Software Developer Radiometer
India India
Currently i am trying to learn all about javascripts . I have experience in Microsoft technologies like WPF, WCF, ASPNET, WinForms,Silverlight, VB.NET, C-Sharp, Entity framework,SSRS, LINQ, Extension methods and SQL server. I started with my career in Infosys in the year 2009 and i worked with Trigent, Education First (EF) in the recent years before joining my current company Radiometer.

You may also be interested in...


Comments and Discussions

QuestionFormat Error Pin
Arsal Hussain25-Oct-17 2:32
memberArsal Hussain25-Oct-17 2:32 
QuestionHow to apply custom style to the exported Excel file Pin
TheKarateKid3-Jun-17 7:23
memberTheKarateKid3-Jun-17 7:23 
GeneralMy vote of 1 Pin
wally7516-Feb-17 1:54
memberwally7516-Feb-17 1:54 
GeneralRe: My vote of 1 Pin
PopoAle28-Jul-17 5:22
memberPopoAle28-Jul-17 5:22 
Questionmultiple integer number not working not working Pin
muthukumaranmca15-Feb-16 2:38
membermuthukumaranmca15-Feb-16 2:38 
GeneralNot a real Excel file Pin
Andestalmoss28-Sep-15 23:45
memberAndestalmoss28-Sep-15 23:45 
QuestionGood Method!!! One ? Pin
Hellfire123128-Jun-15 18:50
memberHellfire123128-Jun-15 18:50 
QuestionThank You so much.. I was in search of this in so many sites, but finally this one is working damn cool.. Pin
RazzSekhar11-May-15 23:18
memberRazzSekhar11-May-15 23:18 
GeneralMy vote of 1 Pin
nabati reza10-Feb-15 1:43
membernabati reza10-Feb-15 1:43 
Bugweak XML generation Pin
sx200826-Nov-14 17:28
membersx200826-Nov-14 17:28 
QuestionHow to create real Excel 2007 files (for free) Pin
Michael Gledhill25-Nov-14 0:36
memberMichael Gledhill25-Nov-14 0:36 
SuggestionMessage Closed Pin
22-Nov-14 10:05
memberCiprian Beldi22-Nov-14 10:05 
QuestionAs this code is only export to excel from datatable , but this code also using gridview for headers Pin
vivek123reddy19-Nov-14 20:07
membervivek123reddy19-Nov-14 20:07 
AnswerRe: As this code is only export to excel from datatable , but this code also using gridview for headers Pin
Santhosh Kumar Jayaraman19-Nov-14 20:26
memberSanthosh Kumar Jayaraman19-Nov-14 20:26 
QuestionThank you Pin
Mahsa Hassankashi15-Sep-14 12:05
memberMahsa Hassankashi15-Sep-14 12:05 
AnswerRe: Thank you Pin
Santhosh Kumar Jayaraman15-Sep-14 21:55
memberSanthosh Kumar Jayaraman15-Sep-14 21:55 
QuestionFor thanks Pin
ram salunke13-Jan-14 23:51
memberram salunke13-Jan-14 23:51 
AnswerRe: For thanks Pin
Santhosh Kumar Jayaraman15-Sep-14 21:54
memberSanthosh Kumar Jayaraman15-Sep-14 21:54 
SuggestionMessage Closed Pin
6-Dec-13 6:34
membernilesh316-Dec-13 6:34 
GeneralNice Work Pin
T Pat8-Aug-13 3:26
professionalT Pat8-Aug-13 3:26 
GeneralGood Example Pin
pankulchitrav17-Jun-13 20:21
memberpankulchitrav17-Jun-13 20:21 
GeneralMy vote of 5 Pin
Juhi Paunikar9-Apr-13 2:07
memberJuhi Paunikar9-Apr-13 2:07 
QuestionHTML/Reflection Pin
ripside@gmail.com24-Feb-13 15:27
memberripside@gmail.com24-Feb-13 15:27 
QuestionHow to hide the columns in the export Pin
90006056673-Jan-13 3:50
member90006056673-Jan-13 3:50 
AnswerRe: How to hide the columns in the export Pin
ripside@gmail.com24-Feb-13 15:29
memberripside@gmail.com24-Feb-13 15:29 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 21 Nov 2014
Article Copyright 2012 by Santhosh Kumar Jayaraman
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid