我有一个需要导出到 Excel 的网格视图。我已设法从行中删除复选框,但不知道如何从标题中删除并完全删除复选框列。感谢帮助。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Select" >
<HeaderTemplate>
<input id="chkAll" onclick="checkAll(this);" runat="server" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Event" HeaderText="Event" SortExpression="Event" />
<asp:BoundField DataField="Event_Description" HeaderText="Event_Description" SortExpression="Event_Description" />
<asp:BoundField DataField="Start_Date" HeaderText="Start_Date" SortExpression="Start_Date" />
</Columns>
</asp:GridView>
这是要导出到 excel 的后端 C# 代码。
protected void download_Click(object sender, EventArgs e)
{
PrepareGridViewForExport(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
GridView1.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(CheckBox))
{
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}