Click here to Skip to main content
15,868,019 members
Articles / Web Development / ASP.NET
Tip/Trick

Export Gridview Data to Excel in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.97/5 (16 votes)
17 Dec 2012CPOL2 min read 377.9K   14.3K   32   47
This tip describes how to export data to an Excel file from a GridView.

Introduction

This tip describes how to export data to an Excel file from a GridView. We will create a sample database and see how the data can be shown in the GridView and then export in Excel format.

Background

There are many scenarios where we would want to export data into Excel format. The data could be from a GridView or from any other data bound control. In this article, we will see how we can export data from a GridView to Excel.

Using the Code

In this tip, I'm trying to explain how to create or export GridView to an MS-Excel file in ASP.NET using C#. I have also placed a button on the page for exporting data to a Microsoft Excel file. We have used a GridView which is bound and a button which will be used to create an Excel file.

For this, I have taken a database named demodb in which there is a table with the following columns:

Now when we have the table structure ready, we have a function for binding the Gridview for which I have used a Dataset. So let us look at the code that fetches data from the database and then binds the data to the grid to display it on the webpage.

C#
protected void fillGrid()
{
    string str = "SELECT [UNo], [EmpName], [Age], 
    	convert(char,[dob],103) dob FROM [tbl_EmpDetails]";

    myConnection = new SqlConnection(conn);
    myConnection.Open();
    myCommand = new SqlCommand(str, myConnection);
    SqlDataAdapter mySQLDataAdapter;
    myDataSet = new DataTable();
    mySQLDataAdapter = new SqlDataAdapter(myCommand);
    mySQLDataAdapter.Fill(myDataSet);
    GridView1.DataSource = myDataSet;
    GridView1.DataBind();
    ViewState["dtList"] = myDataSet;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        fillGrid();
    }
}

Now, after binding a Gridview, data is ready to get exported to an Excel file. We click on a button named Export to Excel. I have used FileInfo to get the information related to the file.

C#
FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
DataGrd.DataBind();

DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}

System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());

The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:

C#
public static void WriteAttachment(string FileName, string FileType, string content)
{
    HttpResponse Response = System.Web.HttpContext.Current.Response;
    Response.ClearHeaders();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.ContentType = FileType;
    Response.Write(content);
    Response.End();
}

Point of Interest

In this tip, we have seen how to export data to an Excel file in ASP.NET. It is rather easy, but many new developers struggle with it so I wrote this to help them.

History

  • 16th October 2012: First version

License

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


Written By
Software Developer
India India
I am a Software Engineer from Bhopal. I started my Career from Programming in ASP and now working as a Web Developer in ASP.Net (C#). I Love coding and always ready to gain new thing and always been towards Microsoft Technologies. Apart from coding my other hobbies are traveling, Internet Surfing, spending time with family and hang out with friends.

http://www.webtekspace.blogspot.in/

Comments and Discussions

 
GeneralMy vote of 5 Pin
Bandi Ramesh15-Feb-13 0:48
Bandi Ramesh15-Feb-13 0:48 
AnswerRe: My vote of 5 Pin
AshishChaudha17-Feb-13 17:55
AshishChaudha17-Feb-13 17:55 
GeneralMy vote of 5 Pin
Mitesh Machhi5-Feb-13 20:22
Mitesh Machhi5-Feb-13 20:22 
AnswerRe: My vote of 5 Pin
AshishChaudha6-Feb-13 7:12
AshishChaudha6-Feb-13 7:12 
GeneralRe: My vote of 5 Pin
Jibesh12-Feb-13 10:14
professionalJibesh12-Feb-13 10:14 
Questionerror occure Pin
Member 81650405-Feb-13 0:02
Member 81650405-Feb-13 0:02 
QuestionThanks Pin
alllaudhin22-Jan-13 0:51
alllaudhin22-Jan-13 0:51 
Questionexport gridview data to excel Pin
priti shrivastava26-Dec-12 3:05
priti shrivastava26-Dec-12 3:05 
In gridview i am using paging concept, when i am exporting the data in excel all dat ais not coming in excel only first page data is coming........

I want when i am click the export button all data will come in the excel ..........
AnswerRe: export gridview data to excel Pin
AshishChaudha26-Dec-12 17:34
AshishChaudha26-Dec-12 17:34 
AnswerRe: export gridview data to excel Pin
karthikreddy08a5030-Jan-13 0:54
karthikreddy08a5030-Jan-13 0:54 
GeneralMy vote of 5 Pin
opv12320-Dec-12 21:05
opv12320-Dec-12 21:05 
AnswerRe: My vote of 5 Pin
AshishChaudha20-Dec-12 21:37
AshishChaudha20-Dec-12 21:37 
QuestionExporting GridView data to excel & PDF with sugession Pin
varaprasadreddy.bh19-Dec-12 7:04
varaprasadreddy.bh19-Dec-12 7:04 
Questionadd some more columns Pin
kamil shaikh17-Dec-12 21:21
kamil shaikh17-Dec-12 21:21 
AnswerRe: add some more columns Pin
AshishChaudha17-Dec-12 21:36
AshishChaudha17-Dec-12 21:36 
Suggestionanother similar article Pin
Lacy0016-Oct-12 22:18
Lacy0016-Oct-12 22:18 
AnswerRe: another similar article Pin
AshishChaudha23-Oct-12 0:16
AshishChaudha23-Oct-12 0:16 
GeneralRe: another similar article Pin
Bandi Ramesh15-Feb-13 22:02
Bandi Ramesh15-Feb-13 22:02 
GeneralMy vote of 5 Pin
Mits Machhi16-Oct-12 18:07
Mits Machhi16-Oct-12 18:07 
AnswerRe: My vote of 5 Pin
AshishChaudha16-Oct-12 18:10
AshishChaudha16-Oct-12 18:10 
AnswerRe: My vote of 5 Pin
AshishChaudha21-May-13 21:28
AshishChaudha21-May-13 21:28 

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.