从gridview导出中删除标题样式到excel

时间:2014-11-07 17:19:52

标签: c# asp.net

在导出到Excel之前,有没有办法可以删除gridview的标题样式和宽度?

这是我当前的导出功能

        Response.Clear();
        Response.Charset = "";
        Response.Buffer = true;
        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}",    "     ExportData.xls"));

        // Prompt for Open/Save/Cancel
        Response.Cache.SetCacheability(HttpCacheability.Private);
        Response.ContentType = "application/vnd.ms-excel";

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

3 个答案:

答案 0 :(得分:1)

我所做的就是在打印到Excel时简单地启动一个新的GridView并用相同的数据填充它。这样,您可以为Excel文件设置单独的设计。

答案 1 :(得分:1)

是的,您可以在导出之前自定义gridview的headerstyle。以下是有关如何执行此操作的示例代码。

var gv = new GridView();
gv.DataSource = reportdata;
gv.DataBind();

// style the header
gv.HeaderRow.Height = Unit.Pixel(35);
gv.HeaderRow.Cells[0].Text = "Some custom header text";
gv.HeaderRow.Cells[0].Width = Unit.Pixel(400);

for (int col = 0; col < gv.HeaderRow.Controls.Count; col++)
{
    TableCell tc = gv.HeaderRow.Cells[col];
    tc.Style.Add("color", "#FFFFFF");
    tc.Style.Add("background-color", "#444");
    tc.Style.Add("border-color", bordercolor);
}

// And your code as follows

Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}",    "     ExportData.xls"));

// Prompt for Open/Save/Cancel
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.ContentType = "application/vnd.ms-excel";

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

gv.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());
Response.End();

答案 2 :(得分:0)

GridView放入div divgrid(类名为divgrid)并使用以下css在打印时隐藏标题。

<style media="print">
    .divgrid thead {
        display: none;
    }
   .divgrid th{
        display: none;
    }
</style>