生成Excel工作表时不要网格视图模板字段

时间:2013-04-09 10:14:21

标签: c# asp.net

我有GridView,我想生成网格列的Excel表格 有生成excel的代码和点击按钮。我的问题是 我不想在Excel工作表的网格视图列中输入模板字段。 我只想要BoundField DataField

<asp:ImageButton ID="btnExcel" runat="server" Text="Excel" ToolTip="Excel"  ImageUrl="~/Images/Resources/thumb/excel.png" OnClick="btnExcel_Click" />
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
    ExportToExcel("Repoet.xls", grdReq);
}


public void ExportToExcel(string strFileName, GridView gv)
{
        HtmlForm form = new HtmlForm();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" +      strFileName);
        Response.ContentType = "application/excel";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        form.Controls.Add(gv);
        this.Controls.Add(form);
        form.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}



<asp:GridView ID="grdReq" runat="server" AutoGenerateColumns="false" CssClass="SimpleGrid"
                OnRowDataBound="grdReq_RowDataBound">
<Columns>
 <asp:BoundField DataField="CandidateID" HeaderText="Candidate Id" />
 <asp:TemplateField>
 <ItemTemplate>
   <asp:HyperLink ID="hlnkEvalSheet" runat="server" Text='<%#Eval("Candidate Name") %>'
    CssClass="logo" NavigateUrl='<%# "~/Recruiter/EvalSheets.aspx?ClientId=" +      hdnClientId.Value  + "&ReqId=" + hdnReqId.Value  %>'
    ImageUrl="~/Images/Resources/search.png" >
    </asp:HyperLink>
 </ItemTemplate>
 </asp:TemplateField>

<asp:BoundField DataField="Candidate Name" HeaderText="Candidate Name" />
<asp:BoundField DataField="Organization" HeaderText="Organization" />                     <asp:BoundField DataField="Desig" HeaderText="Design" /> 
<asp:BoundField DataField="Overall" HeaderText="Overall" />
<asp:BoundField DataField="Qualification" HeaderText="Qualification" /> 
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="Current CTC (LPA)" HeaderText="Current CTC (LPA)" />
</Columns>
</asp:GridView>

1 个答案:

答案 0 :(得分:0)

导出gridview时,从gridview(click here)或主要源和

中检索数据表上的数据时执行一项操作

创建新的gridview对象,如

  Gridview gvexport=new Gridview();
  gvexport.Datasource=dt //retrived data
  gvexport.databind();

使用此gridview生成Excel工作表