Click here to Skip to main content
15,906,333 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi experts,

I have got a requirement that, there I need to export data table to excel
and have to save that excel file in project folder.

I have tried with this sample code but its not working

Quote:
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();


can any one please help me to solve this issue???

thanks
Keerthi Kumar
Posted

Do it in following way
public void ExportToExcel(DataTable dt)
   {
       if (dt.Rows.Count > 0)
       {
           string filename = "Filename.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();

           dgGrid.RenderControl(hw);
           Response.ContentType = "application/vnd.ms-excel";
           Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
           this.EnableViewState = false;
           Response.Write(tw.ToString());
           Response.End();
       }
   }
 
Share this answer
 
Comments
Keerthi Kumar(Andar) 22-Aug-14 1:28am    
Sorry sir am getting this exception

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /MyErrorPage.aspxThread was being aborted.
[no name] 22-Aug-14 1:47am    
this issue something different. This error comes at the time of resource not available. Put try catch to see where is coming and why??
Keerthi Kumar(Andar) 22-Aug-14 1:49am    
ohk..
Keerthi Kumar(Andar) 22-Aug-14 4:40am    
if i remove try catch its working
[no name] 22-Aug-14 8:15am    
then it's fine
I just Removed try catch block for the same posted code its working fine now
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900