Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
I dont have idea on export gridview to excel,pls help me
Posted
Comments
RDBurmon 13-Jun-12 9:32am    
Thanks Everyone who replied to this thread , So Mamtha, I think you have got enough responses and you should be able to mark it as your answer and close the thread. Please do so.

Export Grid To PDF / Excel
Step 1:
public override void VerifyRenderingInServerForm(Control control) { }

Step 2: PDF
public void imgPDFExport_Click(object sender, ImageClickEventArgs e)
{
// gl.Bindgridview("PGetByExperience", "@flag", "Get", gridName);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridName.AllowPaging = false;
gridName.DataBind();
gridName.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr); pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Step 3: Excel
public void imgExcelExport_Click(object sender, ImageClickEventArgs e)
{
ShowData();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridName.AllowPaging = false; gridName.DataBind();
gridName.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridName.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Mahesh Suryawanshi Pune
 
Share this answer
 
Comments
mohamed kalif raja 12-Jun-13 2:51am    
ShowData(); how to define that functionality ?
There are many examples, google it.

Simple example, "in pictures": http://www.gridview.net/export-datagridview-to-excel-in-c/

This way has only to possible problems:
1. Microsoft Office must be installed
2. Sometimes error appears if CurrentCulture is not "EN-US", but you can change it before creating file and restore again after.
 
Share this answer
 
Here is anoher way to export data to excel with enabling excel's default sorting and filtering on columns. also we have the control to set worksheet name. And all this can be achieved without using Interop.

Here is the link
http://blog.weareon.net/export-datatable-to-excel-in-asp-net-without-using-excel-interop-part-ii[^]

Hope this helps
 
Share this answer
 
Comments
Mamtha7 16-Jun-12 3:07am    
thanks
On the button click event try this code
C#
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=GridView1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter StringWriter = new System.IO.StringWriter();
HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
GridView1.RenderControl(HtmlTextWriter);
Response.Write(StringWriter.ToString());
Response.End();


Hope this helps.
 
Share this answer
 
v2
Comments
Mamtha7 16-Jun-12 3:07am    
thanks
Melchizedek1 16-Oct-12 11:36am    
This code saves the entire page in Excel. How do I get just the gridview?

Thanks
C#
#region Export Grid to Excel
        public static void Export(string File, GridView GridView1, string CompanyName, string ReportName, string Criteria1, string Criteria2,int FirstColSpan,int SecColSpan,int ThirdColSpan,int ForthColSpan)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + File);
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Table table = new Table();

            // Report Header Start
            TableRow Tr = new TableRow();
            TableCell TC = new TableCell();
            TC.Text = CompanyName;
            TC.ColumnSpan = FirstColSpan;
            TC.Font.Size = 22;
            TC.Font.Bold = true;
           

            TableCell TC1 = new TableCell();
            TC1.Text = ReportName;
            TC1.ColumnSpan = SecColSpan;
            TC1.Font.Size = 22;
            TC1.Font.Bold = true;
            TC1.HorizontalAlign = HorizontalAlign.Right;
            Tr.Cells.Add(TC);
            Tr.Cells.Add(TC1);

            TableRow Tr1 = new TableRow();
            TableCell TC2 = new TableCell();
            TC2.Text = Criteria1;
            TC2.ColumnSpan = ThirdColSpan;
            TC2.HorizontalAlign = HorizontalAlign.Left;
            TC2.Font.Size = 12;
            TC2.Font.Bold = true;

            TableCell TC3 = new TableCell();
            TC3.Text = Criteria2;
            TC3.ColumnSpan = ForthColSpan;
            TC3.Font.Size = 12;
            TC3.Font.Bold = true;
            TC3.HorizontalAlign = HorizontalAlign.Right;
            Tr1.Cells.Add(TC2);
            Tr1.Cells.Add(TC3);

            table.Rows.Add(Tr);
            table.Rows.Add(Tr1);
            // Report Header End

            //  include the gridline settings
            table.GridLines = GridView1.GridLines;
            if (GridView1.HeaderRow != null)
            {
                //GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                PrepareControlForExport(GridView1.HeaderRow);
                table.Rows.Add(GridView1.HeaderRow);
            }

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                //Change Color back to white
                row.BackColor = System.Drawing.Color.White;
                //Apply text style to each Row
                row.Attributes.Add("class", "textmode");
                //Apply style to Individual Cells of Alternating Row

                //if (i % 2 != 0)
                //{
                //for (int y = 0; y <= row.Cells.Count - 1; y++)
                //{
                //    row.Cells[y].BackColor = System.Drawing.Color.FromName(GetCellcolor(row.Cells[y].Text));

                //}
                // }

            }

            foreach (GridViewRow row in GridView1.Rows)
            {
                //GridViewExportUtil.PrepareControlForExport(row);
                PrepareControlForExport(row);
                table.Rows.Add(row);
                GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
                //TableCell oTableCell = new TableCell();
                //oTableCell.Text = "";
                //oGridViewRow.Cells.Add(oTableCell);
                //PrepareControlForExport(oGridViewRow);
                // table.Rows.Add(oGridViewRow);
            }

            //  add the footer row to the table
            if (GridView1.FooterRow != null)
            {
                //GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                PrepareControlForExport(GridView1.FooterRow);
                table.Rows.Add(GridView1.FooterRow);
            }

            table.RenderControl(hw);
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();



        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    Util.PrepareControlForExport(current);
                    //GridViewExportUtil.PrepareControlForExport(current);
                    PrepareControlForExport(current);
                }
            }
        }
        #endregion
 
Share this answer
 
v2
Comments
Uthman Rahimi 18-Jun-16 0:47am    
what is Util ?
Hi sir:
I have a problem, what is the purpose of the method [VerifyRenderingInServerForm] use for?
 
Share this answer
 
Hi all here is one more solution for grid view export to excel
http://www.dotnetpools.com/2012/09/gridview-export-to-excel-in-aspnet-c.html[^]
 
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