locked
converting a gridview for export to Excel RRS feed

  • Question

  • User-14001990 posted

    Dear All,

    I am trying to export a gridview to Excel.

    I have the code for doing that.The following functions do that:

    public void ExportGridToExcel(GridView grdGridView, string fileName, bool? useExcel)
        {
            //DSAccounts objDSACC = new DSAccounts();
            try
            {
                //String Title = "";
                //if (Request.QueryString["Title"] != null)
                //    Title = Request.QueryString["Title"];

                //Label lblTitle = new Label();
                //lblTitle.Text = Title;
                //lblTitle.Font.Size = FontUnit.Medium;

                Response.Clear();
                Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));

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

                StringWriter stringWrite = new StringWriter();
                HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                htmlWrite.WriteBreak();
                lblTitle.RenderControl(htmlWrite);
                htmlWrite.WriteBreak();
                htmlWrite.WriteBreak();
                grdGridView.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                //ExceptionHandle1 objExp = new ExceptionHandle1();
                //objExp.EH(ex, objDSACC);
                //objExp.LogExceptionInFiles(objDSACC);

                //throw;
            }

        }

     public override void VerifyRenderingInServerForm(Control control)
        {

        }

    There is one more function which takes the values of the controls within the gridview and removes the gridview.

    Now the problem is that the above code works but it creates  Excel sheet without formatting. But I need to format the excel sheet by adding a logo at the top (which I have done) and then write the gridview data within a certain range in the Excel cell.

    I need to send the contents of the gridview in the form of a string and then I am assigning the string to the range value.

    I have changed the above function but the problem is I am getting the content with the HTML markup.

    So how can I get  the gridview contents as a string so that I can assign it as value to the cell range.

    It should be properly formattted so that each grid column comes in a column of the excel sheet.

    Thanks for your reply.

     

    Wednesday, March 18, 2009 10:05 AM

All replies