Click here to Skip to main content
15,921,884 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string attachment = "attachment; filename=Contacts.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);     

        HtmlForm frm = new HtmlForm();           

        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htw);        
        Response.Write(sw.ToString());
        Response.End();


The above code exports grid data into excel but not displays cells of excel.
Posted
Updated 2-Feb-12 1:26am
v2

You can use this Tool
exporttoexcel
 
Share this answer
 
Hi,

Use below link for export to Excel. It is advance and gives proper result with user defined design.

Export to Excel from GridView in C#[^]

It is written by me, if you have any query then you can write to me.
 
Share this answer
 
Hi,

Check out this[^]...
 
Share this answer
 
C#
DataTable xlstable = new DataTable(); 
         string xlsFileName = fileName + " Report";
        HttpContext context = HttpContext.Current;
        context.Response.Clear();

        foreach (DataColumn col in xlstable.Columns)
        {
            context.Response.Write(col.ColumnName + "\t");
        }
        context.Response.Write(Environment.NewLine);

        foreach (DataRow row in xlstable.Rows)
        {
            for (int i = 0; i < xlstable.Columns.Count; i++)
            {
                string content = row[i].ToString().Replace("\t", string.Empty) + "\t";
                context.Response.Write(content);
            }
            context.Response.Write(Environment.NewLine);
        }

        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + xlsFileName + ".xls");
        try
        {
            context.Response.End();
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch (Exception ex)
        {
            string error = ex.Message.ToString();
        }
        finally
        {
            this.Dispose();
        }
 
Share this answer
 
v2
Comments
Anuja Pawar Indore 2-Feb-12 8:05am    
Added pre tag
ram chandar b 2-Feb-12 8:10am    
Thanks. It worked.

Do we have an option of binding table directly to excel without looping?

Please let me know.

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