ASP MVC 3 - 将多表linq查询绑定到gridview并导出到.xls

时间:2013-04-17 20:59:44

标签: asp.net-mvc asp.net-mvc-3 linq gridview export

下面是我在ASP MVC 3控制器中使用的两表linq查询,以导出到.xls文件。但是,我要查询的表与辅助表有一对多的关系。当我单步执行代码时,我可以看到linq查询已按预期执行,FixedStatsVariableStats字段中的信息量正确。但是,当文件导出到spreasheet时,这两列无处可寻。

    public void ExportToCsv()
    {

        var grid = new System.Web.UI.WebControls.GridView();

        //join a in db.BankListAgentId on b.ID equals a.BankID
        var banks = from b in db.BankListMaster

                          where b.Status.Equals("A")
                          select new
                          {
                              BankName = b.BankName,
                              EPURL = b.EPURL.Trim(),
                              AssociatedTPMBD = b.AssociatedTPMBD,
                              Tier = b.Tier,
                              FixedStats = from a in db.BankListAgentId
                                           where a.BankID == b.ID &&
                                                 a.FixedOrVariable.Equals("F")
                                               select new { a.AgentId },
                              VariableStats = from a in db.BankListAgentId
                                              where a.BankID == b.ID &&
                                                    a.FixedOrVariable.Equals("V")
                                              select new { a.AgentId }, 
                               Attachment = b.Attachment,
                              Status = b.Status
                          };

        grid.DataSource = banks.ToList();
        grid.DataBind();

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=BankList.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

1 个答案:

答案 0 :(得分:1)

您可以使用String.JoinAgentId值列表合并为一个字符串,然后将其提供给网格。目前FixedStatsVariableStats是列表,无法显示为网格单元格值:

  select new
  {
      FixedStats = String.Join("|", from a in db.BankListAgentId
                   where a.BankID == b.ID &&
                         a.FixedOrVariable.Equals("F")
                       select a.AgentId.ToString()),
  }

正如Moby的Stunt Double所注意到的,建议创建专用的视图模型。由于ORM< - > SQL转换问题,上述解决方案可能无效。

专用的ViewModel示例:

public class ExportVM
{
    public List<int> FixedStats { get; set; }
    public FixedStatsCombined 
    {
        get
        {
             return String.Join("|", FixedStats.Select(item => item.ToString());
        }
    }
}