从导出到excel的网格视图中删除标题样式

本文关键字:视图 删除 标题 样式 网格 excel | 更新日期: 2023-09-27 18:29:32

在导出到excel之前,有没有办法删除网格视图的标题样式和宽度?

这是我当前的导出功能

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

从导出到excel的网格视图中删除标题样式

是的,您可以在导出之前自定义网格视图的头样式。这是关于如何做到这一点的示例代码

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

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

GridView放在div中,比如divgrid(类名为divgrid),并在打印时使用以下css隐藏页眉。

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