Home » excel » c# – export GridView to excel #2

c# – export GridView to excel #2

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am binding a GridView to a sqldatasource and then on _rowcreated event doing some validations and when the row does not meet requirements I am hiding it using e.Row.Visible = false;

This works fine and only displays the correct rows in the gridview. Now I have a button to export to excel and that works great with the exception of exporting also the hidden rows. I do not want the hidden rows exported.

Is there a way that i can tell the gridview to not add that row instead of hiding it?
Is there a simple method to delete all hidden rows before i run the export?
Can i not add the hidden rows during the export? As you can see in the code below I tried to do this one, but it does not recognize whether the row is visible or not.

Export Code:

 public static void Export(string fileName, GridView gv)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader(
        "content-disposition", string.Format("attachment; filename={0}", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            //  Create a form to contain the grid
            Table table = new Table();

            gv.GridLines = GridLines.Both;
            table.GridLines = gv.GridLines;
            //table.BackColor = Color.Yellow;



            //  add the header row to the table
            if (gv.HeaderRow != null)
            {
                GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                table.Rows.Add(gv.HeaderRow);

                //color the header
                table.Rows[0].BackColor = gv.HeaderStyle.BackColor;
                table.Rows[0].ForeColor = gv.HeaderStyle.ForeColor;
            }

            //  add each of the data rows to the table
            foreach (GridViewRow row in gv.Rows)
            {

                if (row.Visible == true)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }
            }

            //  color the rows
            bool altColor = false;
            for (int i = 1; i < table.Rows.Count; i++)
            {
                if (!altColor)
                {
                    table.Rows[i].BackColor = gv.RowStyle.BackColor;
                    altColor = true;
                }
                else
                {
                    table.Rows[i].BackColor = gv.AlternatingRowStyle.BackColor;
                    altColor = false;
                }
            }

            //  render the table into the htmlwriter
            table.RenderControl(htw);

            //  render the htmlwriter into the response
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
        }
    }
}
How to&Answers:

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html

I have never used GridViewExportUtil, but why not edit his code?

private static void PrepareControlForExport(Control control)
{
    for (int i = 0; i < control.Controls.Count; i++)
    {
        Control current = control.Controls[i];

        //-----------------------------
        // * my addition
        if (!current.Visible) continue;
        //-----------------------------

        if (current is LinkButton)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
        }
        else if (current is ImageButton)
        {
            //...

Answer:

Here is the simple implementation to Export GridView to Excel:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient; 

public partial class ExportGridView : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();

        Response.AddHeader("content-disposition", "attachment;
        filename=FileName.xls");

        Response.Charset = "";

        // If you want the option to open the Excel file without saving than

        // comment out the line below

        // Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.xls";

        System.IO.StringWriter stringWrite = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite =
        new HtmlTextWriter(stringWrite);

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

    }
}

Reference blog

Answer:

In the first place why you have hidden rows from your gridview? Only get data that you wanted. And use this method to export;

void ExportToExcel(GridView grdData, string filename)
{
    grdData.BorderStyle = BorderStyle.Solid;
    grdData.BorderWidth = 1;
    grdData.BackColor = Color.WhiteSmoke;
    grdData.GridLines = GridLines.Both;
    grdData.Font.Name = "Verdana";
    grdData.Font.Size = FontUnit.XXSmall;
    grdData.HeaderStyle.BackColor = Color.DimGray;
    grdData.HeaderStyle.ForeColor = Color.White;
    grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
    grdData.RowStyle.VerticalAlign = VerticalAlign.Top;

    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.Charset = "";
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");

    using (var sw = new StringWriter())
    {
        using (var htw = new HtmlTextWriter(sw))
        {
            grdData.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }
    }
}