如何将所选项目导出到Excel asp mvc

时间:2011-09-12 13:17:32

标签: asp.net asp.net-mvc-2

我想将所选项目导出到Excel中,我将此项目导出到excel但问题是我的头文件已重复我的导出操作方法代码在这里

      public ActionResult ExportExcel(int[] cid)
       {

        var grid = new GridView();
        Response.ClearContent();
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=candidateRecord.xls");
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        var candidate = IcandidateRepository.Candidate.ToList();
        foreach (var candidateid in cid)
        {
            grid.DataSource = from p in candidate where(p.CandidateID==candidateid) select new { name = p.FirstName, companyName = p.Company.CompanyName };


            grid.DataBind();
            grid.RenderControl(hw);
        }
        Response.Write(sw);
        Response.End();![enter image description here][1]
        return view();

}

我的Excel工作表数据在这里请任何人帮我如何删除此重复标题字段

    name    companyName
    sandeep Lear Automotive India
    name    companyName
    sanjay   JSW Steel Limited
    name    companyName
    dabar   Lear Automotive India
    name    companyName
    manoj   jcob
    name    companyName
    kumar   sdf
    name    companyName
    shoaib  Accenture

1 个答案:

答案 0 :(得分:0)

此代码工作正常

  public ActionResult ExportExcel(int[] cid )
    {

        var grid = new GridView();
        Response.ClearContent();

        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=candidateRecord.xls");
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        var candidate = IcandidateRepository.Candidate.ToList();

            grid.DataSource = from p in candidate where cid.Contains(p.CandidateID) select new { name = p.FirstName, companyName = p.Company.CompanyName };


            grid.DataBind();
            grid.RenderControl(hw);

       Response.Write(sw);
        Response.End();
        return View();
    }