从用户控件导出excel

时间:2013-06-08 10:16:51

标签: c# asp.net

我使用以下代码导出gridview数据。这在aspx页面中工作正常。但现在我创建了ascx页面并在此ascx页面中使用相同的代码。但这对我不起作用。请帮我这样做。

try
            {
                DataSet ds = new DataSet();
                ds = (DataSet)Session["Datasource"];
                GridView grid = new GridView();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Record.xls"));
                Response.ContentType = "application/ms-excel";
                grid.DataSource = ds;
                grid.DataBind();
                grid.AllowPaging = false;
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                //Change the Header Row back to white color
                grid.HeaderRow.Style.Add("background-color", "#FFFFFF");
                //Applying stlye to gridview header cells
                for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
                {
                    grid.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
                    grid.FooterRow.Cells[i].Style.Add("background-color", "#507CD1");
                }
                int j = 1;
                //This loop is used to apply stlye to cells based on particular row
                foreach (GridViewRow gvrow in grid.Rows)
                {
                    gvrow.BackColor = System.Drawing.Color.White;
                    if (j <= grid.Rows.Count)
                    {
                        if (j % 2 != 0)
                        {
                            for (int k = 0; k < gvrow.Cells.Count; k++)
                            {
                                gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                            }
                        }
                    }
                    j++;
                }
                grid.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();

            }
            catch (Exception e1)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "onload", "<script language='javascript'>alert('" + e1.Message + "');</script>", false);
            }

1 个答案:

答案 0 :(得分:0)

VerifyRenderingInServerFormPage类的方法,因此您需要将其添加到。{1}} 包含UserControl的页面

public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}