在ASP.NET MVC中返回excel文件响应

时间:2017-11-12 15:26:40

标签: c# asp.net asp.net-mvc excel

我正在构建一个FileResult方法,该方法应该返回一个excel文件。 目前,该方法如下所示:

public ActionResult GetExcelFile(int id)
    {
        var entityPermission = AuthenticationManager.GetEntityPermission(PermissionEntity.Events, PermissionLevel.AllRecords);
        if (entityPermission == null || !entityPermission.AllowRead)
            return Json(new RequestResult(RequestCode.Unauthorized), JsonRequestBehavior.AllowGet);

        try
        {
            using (var serviceManager = new ServiceManager())
            {
                // Get object model
                var firstTableObj = serviceManager.GetDataForExcel(id);
                StringBuilder sb = new StringBuilder();
                sb.Append("<table border=`" + "1px" + "`b>");
                sb.Append("<tr>");
                // ... appending other strings and data
                sb.Append("</table>");

                // Return FileResult
                byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
                return File(new MemoryStream(byteArray, 0, byteArray.Length), "application/octet-stream", $"{firstTableObj.CurrentDate}.xlsx");                   
            }
        }
        catch (Exception ex)
        {
            return Json(new RequestResult(RequestCode.Server_Failure, ex.Message), JsonRequestBehavior.AllowGet);
        }

目前,当我从Angular 2+前端发送请求时,正在处理并返回请求,这是一些标头数据:

Content-Disposition:attachment; filename=12.11.2017.xlsx, Content-Length:617, Content-Type:application/octet-stream

但是,文件没有被下载,响应体只是字符串格式的html模板。我错过了什么?我已经看到了一些在Excel中将excel文件作为FileResult返回的示例,它们与我的没有太大区别。将MIME更改为&#39; application / vnd.ms-excel&#39;也没帮助。另外,据我所知,没有必要在客户端实现任何文件下载逻辑,它应该按原样运行,即来自服务器的响应。 将会欣赏有关该主题的任何提示。

PS:我知道一般情况下我不应该将整个文件加载到内存中,但目前这是用于测试目的(我知道返回文件大小的大致限制),并且在将来的开发中肯定会更改。 / p>

2 个答案:

答案 0 :(得分:0)

你应该改变

public ActionResult GetExcelFile(int id)

public FileResult GetExcelFile(int id)

当然,您无法处理 FileResult 的Json响应。它应该是那样的;

public FileResult GetExcelFile(int id)
        {
            var entityPermission = AuthenticationManager.GetEntityPermission(PermissionEntity.Events, PermissionLevel.AllRecords);
            if (entityPermission == null || !entityPermission.AllowRead)
                //return Json(new RequestResult(RequestCode.Unauthorized), JsonRequestBehavior.AllowGet); 
                //Do something except returning Json response

            try
            {
                using (var serviceManager = new ServiceManager())
                {
                    // Get object model
                    var firstTableObj = serviceManager.GetDataForExcel(id);
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<table border=`" + "1px" + "`b>");
                    sb.Append("<tr>");
                    // ... appending other strings and data
                    sb.Append("</table>");

                    // Return FileResult
                    byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
                    return File(new MemoryStream(byteArray, 0, byteArray.Length), "application/octet-stream", $"{firstTableObj.CurrentDate}.xlsx");                   
                }
            }
            catch (Exception ex)
            {
                //Do something except returning Json response
            }
}

答案 1 :(得分:0)

You are not saving an xlsx file. You are saving an html file with xlsx extension.

You probably adjusted a sample found on the internet, but the initial extension was xls.

An html file with xls extension is not an Excel file either, but MS Excel knows to render the html file and displays the file into the spreadsheet. Still, with the recently MS Excel version a warning is raised that is an invalid file format.

If you need to save xlsx files, you need to search for an Excel library like OpenXML from Microsoft, EPPlus open source or EasyXLS commercial with 30-days trial.