Click here to Skip to main content
Click here to Skip to main content

Export Gridview Data to Excel in ASP.NET

By , 17 Dec 2012
 

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.

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.

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:

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)

About the Author

AshishChaudha
Software Developer
India India
Member
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/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionexporting grid view data to excelmemberMember 100478478hrs 39mins ago 
i have a function in which i'm exporting grid view data into excel. the problem i'm facing is i have a datetime field in gridview having format dd/MM/yyyy and when it is exported in excel it automatically changes to MM/dd/yyyy for date less = 12 and in rest of cases it shows dates in dd/MM/yyyy format
QuestionExport to Excelmemberalexk1957199420 Feb '13 - 3:49 
Your article is nice and works for me.
But I want to format programmatically headers of my table (the first line of Excel spreadsheet)- take them color of border, background, font etc.
And vice versa I want to supress these headers - to print a spreadsheet without them.
What must I do?
QuestionMy vote of 5memberbandi.ramesh15 Feb '13 - 22:04 
Superb explanation. No doubts. Thanks you
AnswerRe: My vote of 5professionalAshishChaudha7 Apr '13 - 17:56 
Thanks bandi.ramesh
GeneralMy vote of 5memberbandi.ramesh15 Feb '13 - 0:48 
My vote of 5
AnswerRe: My vote of 5memberAshishChaudha17 Feb '13 - 17:55 
Thanks ramesh
Questionnice onememberMember 382310115 Feb '13 - 0:24 
hi this is really a nice article . have a look of this also
http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=22&title=Gridview-Export-To-Excel-In-Asp.Net-C#[^]
GeneralMy vote of 5memberMitesh Machhi5 Feb '13 - 20:22 
my 5 for this. nice and easy to understand.
AnswerRe: My vote of 5memberAshishChaudha6 Feb '13 - 7:12 
thanks
GeneralRe: My vote of 5 [modified]memberJibesh12 Feb '13 - 10:14 
Mitesh You have already got the treatment for sockpuppeting and regardless of the advice from the forum moderators, you continue do the same will yield another ban from this site. Please stop doing this, mods in CP are smart enough to locate these people. If you want to stay in CP be adhere to the forum rules.
 
FYI: mods are watching your activities.


modified 12 Feb '13 - 16:22.

Questionerror occurememberMember 81650405 Feb '13 - 0:02 
After running this code, in the
System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
gives me a error
"A required privilege is not held by the client."
 
pls help me to resolve this problem.
QuestionThanksmemberalllaudhin22 Jan '13 - 0:51 
Laugh | :laugh:
Questionexport gridview data to excelmemberpriti 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 excelmemberAshishChaudha26 Dec '12 - 17:34 
I only added following code line for paging concept and it is working fine.
 
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
   {
       GridView1.PageIndex = e.NewPageIndex;
       fillGrid();
   }
 

Thanks
AnswerRe: export gridview data to excelmemberkarthikreddy08a5030 Jan '13 - 0:54 
Gridview1.paging=false;
 
add this code under export excel button it will work
K@arthik

GeneralMy vote of 5memberopv12320 Dec '12 - 21:05 
nice code
AnswerRe: My vote of 5memberAshishChaudha20 Dec '12 - 21:37 
Thanks
QuestionExporting GridView data to excel & PDF with sugessionmembervaraprasadreddy.bh19 Dec '12 - 7:04 
Hi please check out this it may help some one...
Excel :
http://reddyinfosoft.blogspot.in/2012/08/export-gridview-data-to-excel-using.html[^]
 
PDF :
http://reddyinfosoft.blogspot.com/2012/08/export-gridview-data-to-pdf-using.html[^]
 
and Word :
 
http://reddyinfosoft.blogspot.com/2012/08/export-gridview-data-to-word-using.html
Questionadd some more columnsmemberkamil shaikh17 Dec '12 - 21:21 
after doing this i want to add some more columns and their values in that existing excel in background
please give me any suggestion..

 
thnx
AnswerRe: add some more columnsmemberAshishChaudha17 Dec '12 - 21:36 
Add the required columns and their values in datatable on click of the Export to Excel button.
Suggestionanother similar articlememberLacy0016 Oct '12 - 22:18 
Thanks for sharing such greate article here, I also know another similar article on export to excel topic, it is also useful. I think I should suggest to all of you: 9 Solutions to Export Data to Excel for ASP.NET[^]
AnswerRe: another similar articlememberAshishChaudha23 Oct '12 - 0:16 
Thanks for sharing..
GeneralRe: another similar articlememberbandi.ramesh15 Feb '13 - 22:02 
Thanks
GeneralMy vote of 5memberMits Machhi16 Oct '12 - 18:07 
nice 1
AnswerRe: My vote of 5memberAshishChaudha16 Oct '12 - 18:10 
Thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 17 Dec 2012
Article Copyright 2012 by AshishChaudha
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid