将Gridview的选定行下载到excel

时间:2013-01-01 11:38:13

标签: c# asp.net excel

我需要将选定的asp.net gridview行下载到Excel工作表。 我正在做的是立即尝试检查或只选择几个,然后在按下面的下载按钮后,所有选定的行将作为excel下载。当我按下下载按钮时,每件事情都可以正常工作,而是忽略选择而下载所有行。 Grid View Sample 以下是我的代码

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");
    }
}

2 个答案:

答案 0 :(得分:0)

我可以建议你这样做的逻辑:

1.使用gridview的选定行创建动态数据表。   它只是循环遍历gridview行并获取并将所选行附加到新数据表。

2.然后编写将此新数据表转换为excel表格的代码(google“将数据转换为excel”的大量结果)

答案 1 :(得分:0)

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

在下载按钮单击事件中,调用此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();

}