简体   繁体   中英

Download Selected Row of Gridview to excel

I need to download selected rows of an asp.net gridview to an excel sheet. What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection. 网格视图样本 Following is my code

public void ExportGridToExcel(GridView grdGridView, string fileName)
{
    Response.Clear();

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

    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

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

    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

// I Tried using following (but with no success)
//-----Trial Starts----------------
//foreach (GridViewRow gvr in gvProgramList.Rows)
//    {
//        CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
//        if(cbox.Checked)
//            gvr.Visible = true;
//        else
//            gvr.Visible = false;
//    }
//--------Trial ends---------------
    grdGridView.DataBind();
    ClearControls(grdGridView);

    // Throws exception: Control 'ComputerGrid' of type 'GridView'
    // must be placed inside a form tag with runat=server.
    // ComputerGrid.RenderControl(htmlWrite);

    // Alternate to ComputerGrid.RenderControl above
    System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
    Controls.Add(form);



    form.Controls.Add(grdGridView);
    form.RenderControl(htmlWriter);
    Response.Write(stringWriter.ToString());
    Response.End();
    foreach (GridViewRow gvr in gvProgramList.Rows)
    {
        CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
            gvr.Visible = true;
    }
    grdGridView.DataBind();
}

private void ClearControls(Control control)
{
    for (int i = control.Controls.Count - 1; i >= 0; i--)
    {
        ClearControls(control.Controls[i]);
    }

    if (!(control is TableCell))
    {
        if (control.GetType().GetProperty("SelectedItem") != null)
        {
            LiteralControl literal = new LiteralControl();
            control.Parent.Controls.Add(literal);
            try
            {
                literal.Text =
                    (string)control.GetType().GetProperty("SelectedItem").
                        GetValue(control, null);
            }
            catch
            { }
            control.Parent.Controls.Remove(control);
        }
        else if (control.GetType().GetProperty("Text") != null)
        {
            LiteralControl literal = new LiteralControl();
            control.Parent.Controls.Add(literal);
            literal.Text =
                (string)control.GetType().GetProperty("Text").
                    GetValue(control, null);
            control.Parent.Controls.Remove(control);
        }
    }
    return;
}

protected void btnDownload_Click(object sender, EventArgs e)
{
    if (gvProgramList.Rows.Count > 0)
    {
        ExportGridToExcel(gvProgramList, "ProgramList");
    }
}

I can suggest you a logic to do this:

1.Create a dynamic datatable with selected rows of your gridview. its just looping through gridview rows and fetching and appending selected rows to new datatable.

2.Then write code for converting this new datatable to excel sheets(lots of results for google "Convert datatable to excel")

Try like the below code,hope it helps you..

On the download button click event,call this fn

private void ExportToExcell()
{       
        DataTable dt = new DataTable();
        dt.Columns.Add("Plan ID");
        dt.Columns.Add("Plan Name");
        dt.Columns.Add("Balance");
        foreach (GridViewRow row in gdvBal.Rows)
        {
            CheckBox chkCalls = (CheckBox)row.FindControl("chkCalls");
            if (chkCalls.Checked == true)
            {
                int i = row.RowIndex;
                Label lblPlanId = (Label)gdvBal.Rows[i].FindControl("lblPlanId");
                Label lblPlanName = (Label)gdvBal.Rows[i].FindControl("lblPlanName");
                Label lblBalance = (Label)gdvBal.Rows[i].FindControl("lblBalance");

                DataRow dr = dt.NewRow();
                dr["Plan ID"] = Convert.ToString(lblPlanId.Text);
                dr["Plan Name"] = Convert.ToString(lblPlanName.Text);
                dr["Balance"] = Convert.ToString(lblBalance.Text);
                dt.Rows.Add(dr);
            }
        }
        GridView gdvExportxls = new GridView();
        gdvExportxls.DataSource = dt;
        gdvExportxls.DataBind();
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("content-disposition", string.Format("attachment;filename=BillingForfBalances.xls", "selectedrows"));
        Response.Charset = "";
        StringWriter stringwriter = new StringWriter();
        HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
        gdvExportxls.RenderControl(htmlwriter);
        Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
        Response.End();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM