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

Export to EXCEL from Datatable in C#.Net

Rate me:
Please Sign up or sign in to vote.
2.91/5 (12 votes)
12 Mar 2012CPOL 276.1K   20   14

Introduction

Export the Datatable records to Excel sheet in C#.net 

Using the code 

This below function used to generate excel file based on datatable.

C++
public void ExportToExcel(DataTable dt)
{
	if (dt.Rows.Count > 0)
	{
		string filename = "DownloadMobileNoExcel.xls"; 
		System.IO.StringWriter tw = new System.IO.StringWriter();
		System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
		DataGrid dgGrid = new DataGrid();
		dgGrid.DataSource = dt;
		dgGrid.DataBind();

		//Get the HTML for the control.
		dgGrid.RenderControl(hw);
		//Write the HTML back to the browser.
		//Response.ContentType = application/vnd.ms-excel;
		Response.ContentType = "application/vnd.ms-excel";
		Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
		this.EnableViewState = false;
		Response.Write(tw.ToString());
		Response.End();
	}
}

 Call the above function in button click event

C++
protected void btnSave_Click(object sender, EventArgs e)
{
    ExportToExcel((DataTable)ViewState["gvMobile"]);  
}
C++
public override void VerifyRenderingInServerForm(Control control)

{ 

} 

 

License

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


Written By
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHi Pin
Sarathkumar Nallathamby3-Aug-12 20:48
professionalSarathkumar Nallathamby3-Aug-12 20: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.