Click here to Skip to main content
15,911,035 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am generating a table through .cs page which works on click event.
i am interested in exporting that table being generated dynamically as an excel file,
can anyone help!


any ideas! please help!

even google cud nt solve d prblm
all the soltion provided had datagrid bt i havnt used that


My code goes like this for table generation:

C#
protected void Button1_Click(object sender, EventArgs e)
    {
 Response.Write("<table width="100%" height="210">");

        Response.Write("<tr bgcolor="#D1D7B5">"); // start: display header
        Response.Write("<td valign="top" width="50px">");
        Response.Write("<center>");
        Response.Write("<font size="4" color="#444444">");
        Response.Write("");
        Response.Write("");
        Response.Write("");
        Response.Write("</font>");
        Response.Write("</center>");
        Response.Write("</td>");

        Response.Write("<td valign="top" width="130px">");
        Response.Write("<font size="3" color="#444444">");
        Response.Write("");
        Response.Write(" ");
        Response.Write("Grand Total");
        Response.Write("");
        Response.Write("</font>");
        Response.Write("</td>");

               da2 = new SqlDataAdapter(years, connec);
        dt2 = new DataTable();
        da2.Fill(dt2);

        for (int j = 0; j < dt2.Rows.Count; j++)
        {
            if (yyyy1 == yyyy2)
            {
                str2 = findvalue("select count(CaseStatus) as CaseStatus1 from PROPOSAL  where    CaseStatus='" + cases + "'and datefinal between'" + strtdate + "'and'" + enddate + "'");
                if (str2 == "0")
                {
                    str3 = "0";
                }
                else
                {

                    str3 = findvalue("select sum(AreaDiverted) as AreaDiverted from PROPOSAL where    CaseStatus='" + cases + "'and datefinal between'" + strtdate + "'and'" + enddate + "'");
                }                    //strtdate = clm1;
            }
            else
            {
                nxtend = dt1.Rows[j][0].ToString() + "/12/31";
                str2 = findvalue("select count(CaseStatus) as CaseStatus1 from PROPOSAL  where    CaseStatus='" + cases + "'and datefinal between'" + strtdate + "'and'" + nxtend + "'");

                if (str2 == "0")
                {
                    str3 = "0";
                }
                else
                {

                    str3 = findvalue("select sum(AreaDiverted) as AreaDiverted from PROPOSAL where    CaseStatus='" + cases + "'and datefinal between'" + strtdate + "'and'" + nxtend + "'");

                }
                if (j + 1 != dt1.Rows.Count)
                {
                    strtdate = dt1.Rows[j + 1][0].ToString() + "/01/01";
                }
                yyyy1 = Convert.ToString(Convert.ToInt16(yyyy1) + 1);
            }

            Response.Write("<td align="center" width="7%>");<br" mode="hold" />            Response.Write("<center>");
            Response.Write("<font size="3" color="#444444">");
            Response.Write("");
            Response.Write(str2);
            Response.Write("");
            Response.Write("</font>");
            Response.Write("</center>");
            Response.Write("");

            Response.Write("<td valign="top" width="7%">");
            Response.Write("<center>");
            Response.Write("<font size="3" color="#444444">");
            Response.Write("");
            Response.Write(str3);
            Response.Write("");
            Response.Write("</font></center>");
            Response.Write("");
            Response.Write("</td>");
        }

  //Response.Write("");

        Response.Write("</tr>");


       //Response.Write(""); //end line
        Response.Write("</table>");
        Response.Write("       // Response.Write("</body>");
        // Response.Write("</html>");

    }
Posted
Updated 11-Nov-11 1:09am
v7
Comments
OriginalGriff 11-Nov-11 6:22am    
DON'T SHOUT. Using all capitals is considered shouting on the internet, and rude (using all lower case is considered childish). Use proper capitalisation if you want to be taken seriously.
OriginalGriff 11-Nov-11 6:23am    
Reason for my vote of one: too lazy to use google.

Mr Google can help: Google[^]

Please try to do at least a basic search before you post a question, or you just waste your time and ours.
 
Share this answer
 
Comments
rasaurabh 11-Nov-11 6:27am    
i hav already done dat
bt of no use
my data is not in a datagrid
instead i hav used multiple queries becoz of multipple table incusion
 
Share this answer
 
Comments
rasaurabh 11-Nov-11 6:32am    
data is not stored in a datatable
instead each column value is being calculated thru stored procedure
Try this Code then tell me

public void ExportHtmlTabletoExcel()

        {


            try

            {

                Response.Clear();

                Response.Buffer = true;

                this.EnableViewState = false;

                string attachment = "attachment;   filename=yourPageName.xls";

                Response.AddHeader("content-disposition", attachment);

                Response.ContentType = "application/ms-excel";

                StringWriter sw = new StringWriter();

                HtmlTextWriter htw = new HtmlTextWriter(sw);

                HtmlForm frm = new HtmlForm();

                panReport.Parent.Controls.Add(frm);

                frm.Attributes["runat"] = "server";

                frm.Controls.Add(panReport);

                frm.RenderControl(htw);

                Response.Write(sw.ToString());

                Response.End();

            }

            catch (Exception ex)

            {

                throw ex;

            }
        }

         public override void VerifyRenderingInServerForm(Control control)

        {

            /* Verifies that the control is rendered */


        }

protected void imgbtnExcel_Click(object sender, ImageClickEventArgs e)

        {

            try

            {

                ExportHtmlTabletoExcel()

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

    }

In ur Page Directive use this property because sometimes it confers error without this property EnableEventValidation="false"


[Edited]Code is wrapped in "pre" tag[/Edited]
 
Share this answer
 
v2
Comments
RaviRanjanKr 13-Nov-11 2:04am    
A suggestion :- Always wrap your code in "pre" tag. it gives better readability to other users.
rasaurabh 14-Nov-11 6:34am    
still no solution people, an html page is being generated through a .cs page coding.Hence its id needs to be rendered which is the main problem please have a look at the table and the way data is being fetched from the database
and suggest a solution for the same
Hi dude,
try this code to rectify ur problem make function store ur dt or ds whatever u have taken store it in viewstate and then cast it

the code shown below

C#
public void fillgrid()
    {
        DataTable dt = new DataTable();
        dt = Employee.selectgrid();
        grdArea.DataSource = dt;
        grdArea.DataBind();
    }

 public void convertexcel()
    {
            try
            {
                Response.Clear();
                // ExportGridExel();
                GridView grdExcel = new GridView();
                grdExcel.AutoGenerateColumns = true;
                DataTable dtExcel = (DataTable)ViewState["viewRecordEX"];
                grdExcel.DataSource = (DataTable)ViewState["viewRecordEX"];
                grdExcel.DataBind();
                //Set the content type to Excel.
                grdExcel.AllowPaging = false;
                
                //Set the content type to Excel.
                Response.ContentType = "application/excel";   //ViewofEmployeeMaster.ms-excel
                Response.AddHeader("content-disposition", "attachment;filename=ViewofEmployeeMaster.xls");
                //Remove the charset from the Content-Type header.
                Response.Charset = "";
                //Turn off the view state.
                this.EnableViewState = false;
                System.IO.StringWriter tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                //code written for excel 
                HtmlForm frm = new HtmlForm();
                frm.Attributes.Add("ID", "frm");  // form1   //frm1
                frm.Attributes.Add("runat", "Server");


                GridViewRow row1 = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
                TableCell rowheader1 = new TableHeaderCell();
                rowheader1.Text = "EMPLOYEE MASTER RECORDS";
               //rowheader1.BorderWidth = 0;
                rowheader1.ColumnSpan = 12;
                rowheader1.Font.Size = 20;
                rowheader1.HorizontalAlign = HorizontalAlign.Left;
                row1.Cells.Add(rowheader1);
                Table t1 = grdExcel.Controls[0] as Table;
                if (t1 != null)
                {
                    t1.Rows.AddAt(0, row1);
                }
                ////Add  Header Text
                //GridViewRow row = new GridViewRow(1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                //TableCell totals = new TableCell();
                ////  totals.ColumnSpan = 18;
                //totals.Text = ViewState["empname"].ToString() + " - " + ddlSubQruery.SelectedItem.Text;
                //totals.BorderWidth = 0;
                //totals.HorizontalAlign = HorizontalAlign.Center;
                //totals.ColumnSpan = 8;
                //row.Cells.Add(totals);
                //Table t = gvViewRecordEmp.Controls[0] as Table;
                //if (t != null)
                //{
                //    t.Rows.AddAt(1, row);
                //}
                //Add Blank Row
                GridViewRow rowblk5 = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
                TableCell tblblnk5 = new TableCell();  //TableHeaderCell()
                tblblnk5.BorderWidth = 0; 
                //tblblnk.ColumnSpan = 18;
                rowblk5.Cells.Add(tblblnk5);
                Table tblk5 = grdExcel.Controls[0] as Table;
                if (tblk5 != null)
                {
                    tblk5.Rows.AddAt(1, rowblk5);
                }
                //Add Blank Header
                //GridViewRow rowblk = new GridViewRow(2, -1, DataControlRowType.Header, DataControlRowState.Normal);
                //TableCell tblblnk = new TableHeaderCell();
                //tblblnk.BorderWidth = 0;
                //tblblnk.ColumnSpan = 18;
                //rowblk.Cells.Add(tblblnk);
                //Table tblk = grdArea.Controls[0] as Table;
                //if (tblk != null)
                //{
                //    tblk.Rows.AddAt(2, rowblk);
                //}
                frm.Controls.Add(grdExcel);
                // gvViewRecordEmp.Columns[6].Visible = false;
                //  gvViewRecordEmp.Columns[5].Visible = false;
                //end code
                //Get the HTML for the control.
                grdExcel.RenderControl(hw);
                //Write the HTML back to the browser.
                Response.Write(tw.ToString());
                //End the response.
                Response.End();
            }
            catch (Exception ex)
            {
                throw ex;

            }
        }
 
Share this answer
 
v2

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