MVC4 Linq加入查询结果并导出到.XLS

时间:2013-12-04 15:41:45

标签: c# linq excel

我是C#和MVC的新手,在尝试将数据从linq查询导出到csv / excel时我感到很难过。我试图保持这个尽可能简单,而不必使用任何插件。我环顾四周,发现了很多将查询导出到excel的方法,但我在某处遗漏了一些东西。

这是我的控制器

    public void ExportData(string searchString)
    {
        GridView grid = new GridView();

        var stuff =
           from ocs in db.OCS
           join o in db.OCSSoftwares
               on new { ocs.name, ocs.version } equals new { o.name, o.version }
           join l in db.LicModels
               on o.licModelId equals l.id
           join s in db.SoftwareTypes
               on l.softwareType equals s.type

           select new InstallvsLicense { softname = o.name, version = o.version, licmodname = l.name, vendor = l.softwareVendor, softtype = l.softwareType, pcname = ocs.pcName, facility = ocs.facility, requirespo = s.requiresPO, toberemoved = l.toBeRemoved };

            stuff = stuff.Where(s =>
            (s.facility.Contains(searchString)) &&
            ((s.requirespo.Value.Equals(true)) ||
            (s.toberemoved.Value.Equals(true)))).OrderBy(s => s.softname);

            grid.DataSource = stuff.ToList();
            grid.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=" + searchString.ToUpper() + " Remediation Report.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grid.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

        ViewBag.searchString = searchString;
        RedirectToAction("Remediation");
    }

在我的索引控制器方法中,我从同一个linq查询中核心地接收数据,但在这个方法中,我收到一个“{”对象引用未设置为对象的实例。“}”错误,当内部异常为null时我单击以下行中的导出

Response.AddHeader("content-disposition", "attachment; filename=" + searchString.ToUpper() + " Remediation Report.xls");

有人能告诉我我做错了吗?

0 个答案:

没有答案