导出gridview后,在excel标题中删除图像

时间:2011-09-02 11:17:43

标签: asp.net vb.net

请帮我详细说明如何删除excel标题中的图片。我使用gridview作为源数据使用export命令生成excel

这是我的代码

Response.AddHeader("content-disposition", "attachment;filename=" & strFilename & ".xls")
        Response.Clear()
        Response.Charset = ""
        Response.ContentType = "application/vnd.xls"


        Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
        Dim htw As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(sw)


        grvData.AllowPaging = False
        grvData.AllowSorting = False
        PopulateGrid()

        grvData.RenderControl(htw)
        Response.Write(sw.ToString)
        Response.End()

一切都被设置了 - 除了我的标题有一个空白的标题名称,因为现在显示的图像 - 图像来自gridview(我使用箭头为asc和desc) - 抱歉,我无法发布任何图像现在在这里

1 个答案:

答案 0 :(得分:0)

给这个ClearControls方法一个机会。它应该在导出之前从网格中删除任何控件:

protected void btnExport_Click(object sender, EventArgs e)
{       
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";

    System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

    this.ClearControls(DataGrid1);
    DataGrid1.RenderControl(oHtmlTextWriter);

    DataGrid1.GridLines = GridLines.Both;
    DataGrid1.Style.Clear();

    Response.Write(oStringWriter.ToString());
    Response.End();
}

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
            { 
                //do nothing 
            }
            finally
            { 
                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;
}