EPPlus不下载带有模板的Excel文件

时间:2018-10-09 03:02:00

标签: c# asp.net-mvc epplus

当我使用Epplus导出excel时,没有下载excel文件,这是我的代码

public ActionResult ExportDataTableToExcel(string searchBox)
{
    FileStream fs = null;
    var fileName = "xxxReport";

    fs = new FileStream(Server.MapPath(@"~/Content/Templates/xxxReport.xlsx"), FileMode.Open, FileAccess.Read);

    var result = new List<xxxReport_Result>();
    using (var db = new xxxEntities())
    {
        if (searchBox != "" && searchBox != null)
        {
            result = db.xxxReport()
                    .Where(r => r.Match.Contains(searchBox)
                    || r.MD.Contains(searchBox)
                    || r.SBU.Contains(searchBox)
                    || r.Project.Contains(searchBox)).ToList();
        }
        else
        {
            result = db.xxxReport().ToList();
        }
    }

    var results = Mapper.Map<List<ReportModel>>(result);

    Debug.WriteLine("End : {0}", DateTime.Now.ToString("HH:mm:ss"));

    using (var excel = new ExcelPackage(fs))
    {
        var workSheet = excel.Workbook.Worksheets.FirstOrDefault();

        int i = 11;
        results.ToList().ForEach(s =>
            {
                int col = 2;
                workSheet.Cells[i, col++].Value = s.NO;
                workSheet.Cells[i, col++].Value = s.Match;
                workSheet.Cells[i, col++].Value = s.MD;
                workSheet.Cells[i, col++].Value = s.SBU;
                workSheet.Cells[i, col++].Value = s.Project;
                workSheet.Cells[i, col++].Value = s.BlockUnit;
                i++;
            });

        Response.Clear();
        string saveAsFileName = string.Format("{0}_{1:d}.xlsx", fileName, DateTime.Now).Replace("/", "-");
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", saveAsFileName));
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.BinaryWrite(excel.GetAsByteArray());
        Response.End(); 
    }
    return JavaScript("Export Complete");
}

当我点击导出按钮时,我没有得到提示,我尝试调试并且代码中没有错误,但是当使用console.log检查结果时,我在结果中得到了我喜欢的东西。

  

���ʮ�����O�&�ת������o����Tҵ��B*���]��(S���d�Ŗ��)。 ``Oe���Ťp> ^����4aπT|����4��_。

这就是我调用函数的方式

function ExportToExcel() {
        $.post("@Url.Action("ExportDataTableToExcel", "xxx")",
        {
            searchBox1: $("#searchBox1").val(),
            searchBox2: $("#searchBox2").val(),
            searchBox3: $("#searchBox3").val(),
            searchBox4: $("#searchBox4").val()
        }).done(function (result) {
            console.log(result);
        });
    }

2 个答案:

答案 0 :(得分:2)

使用MVC时,除非绝对需要,否则应避免直接与Response对象进行交互。考虑到这一点,这应该起作用:

public ActionResult ExportDataTableToExcel(string searchBox)
{
    var fileName = "xxxReport";
    byte[] excelContent;

    // *** code that pulls your data ***

    // always try to use a 'using' statement when you can for disposable objects
    using (var fs = new FileStream(Server.MapPath(@"~/Content/Templates/xxxReport.xlsx"), FileMode.Open, FileAccess.Read))
    using (var excel = new ExcelPackage(fs))
    {
        // *** manipulate your worksheet here ***

        excelContent = excel.GetAsByteArray();
    }

    string saveAsFileName = string.Format("{0}_{1:d}.xlsx", fileName, DateTime.Now).Replace("/", "-");
    return File(excelContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", saveAsFileName);
}

MVC控制器函数返回一个许多其他类都继承的ActionResult对象,包括System.Web.Mvc.FileContentResult函数返回的File()(此方法内置于System.Web.Mvc.Controller中)

答案 1 :(得分:0)

我通过创建另一个函数来修复该问题,该函数使用“ GET”方法下载结果文件