2011-09-12 48 views
0

我想選擇的項目導出到Excel和我出口這一項目到Excel,但問題是我的頭提起重複我的導出操作方法的代碼是在這裏如何選定項目導出到Excel中的ASP MVC

 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 
+0

您不應該在ASP.NET MVC中以這種方式使用'Response.Whatever()'。 [去做一些不錯的ASP.NET MVC教程](http://www.asp.net/mvc)! :) – bzlm

+0

我得到了使用linq查詢的解決方案 –

回答

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