Click here to Skip to main content
15,506,025 members
Articles / Web Development / ASP.NET
Tip/Trick
Posted 16 Oct 2012

Stats

364.6K views
14.2K downloads
32 bookmarked

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
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

 
QuestionFile Format or Extension not matched! Pin
Member 1221028227-Oct-17 21:44
Member 1221028227-Oct-17 21:44 
QuestionDownload excel file not working Pin
Member 1239294311-Dec-16 19:19
Member 1239294311-Dec-16 19:19 
AnswerRe: Download excel file not working Pin
djramc12-Feb-17 11:40
djramc12-Feb-17 11:40 
GeneralMy vote of 5 Pin
Deepak Rana1119-Dec-13 1:50
professionalDeepak Rana1119-Dec-13 1:50 
AnswerRe: My vote of 5 Pin
AshishChaudha19-Dec-13 1:55
AshishChaudha19-Dec-13 1:55 
QuestionOK Pin
Deepak Rana1119-Dec-13 1:12
professionalDeepak Rana1119-Dec-13 1:12 
GeneralMy vote of 4 Pin
Rachelle Villar22-Aug-13 21:58
Rachelle Villar22-Aug-13 21:58 
AnswerRe: My vote of 4 Pin
AshishChaudha22-Aug-13 22:04
AshishChaudha22-Aug-13 22:04 
QuestionPath does not work Pin
Manish Bhardwaj4-Jul-13 18:42
Manish Bhardwaj4-Jul-13 18:42 
QuestionMessage Closed Pin
3-Jun-13 11:17
Member 87073803-Jun-13 11:17 
AnswerRe: Hi Code is working fine but not working on Server Pin
jonlink013-Jun-13 12:07
jonlink013-Jun-13 12:07 
AnswerRe: Hi Code is working fine but not working on Server Pin
AshishChaudha3-Jun-13 18:49
AshishChaudha3-Jun-13 18:49 
GeneralRe: Hi Code is working fine but not working on Server Pin
jonlink013-Jun-13 22:31
jonlink013-Jun-13 22:31 
AnswerRe: Hi Code is working fine but not working on Server Pin
AshishChaudha3-Jun-13 23:51
AshishChaudha3-Jun-13 23:51 
GeneralRe: Hi Code is working fine but not working on Server Pin
jonlink014-Jun-13 22:57
jonlink014-Jun-13 22:57 
GeneralRe: Hi Code is working fine but not working on Server Pin
AshishChaudha5-Jun-13 0:58
AshishChaudha5-Jun-13 0:58 
GeneralRe: Hi Code is working fine but not working on Server Pin
jonlink015-Jun-13 6:53
jonlink015-Jun-13 6:53 
GeneralMessage Closed Pin
5-Jun-13 9:14
Member 87073805-Jun-13 9:14 
AnswerRe: Hi Code is working fine but not working on Server Pin
AshishChaudha5-Jun-13 19:05
AshishChaudha5-Jun-13 19:05 
Questionexporting grid view data to excel Pin
Member 1004784721-May-13 0:50
Member 1004784721-May-13 0:50 
AnswerRe: exporting grid view data to excel Pin
AshishChaudha21-May-13 22:27
AshishChaudha21-May-13 22:27 
QuestionExport to Excel Pin
alexk1957199420-Feb-13 4:49
alexk1957199420-Feb-13 4:49 
QuestionMy vote of 5 Pin
Bandi Ramesh15-Feb-13 23:04
Bandi Ramesh15-Feb-13 23:04 
AnswerRe: My vote of 5 Pin
AshishChaudha7-Apr-13 18:56
AshishChaudha7-Apr-13 18:56 
GeneralMy vote of 5 Pin
Bandi Ramesh15-Feb-13 1:48
Bandi Ramesh15-Feb-13 1:48 

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.