简体   繁体   English

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

[英]Return excel file response in ASP.NET MVC

I am building a FileResult method which is supposed to return an excel file as a result. 我正在建立一个FileResult方法,该方法应该返回一个excel文件。 Currently the method looks like this: 当前该方法如下:

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

Currently, when I send a request from Angular 2+ frontend, the request is being processed and returned, this is some of the header data: 当前,当我从Angular 2+前端发送请求时,该请求正在处理并返回,这是一些标头数据:

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

However, the file is not being downloaded, the response body is just the html template in string format. 但是,该文件未下载,响应主体只是字符串格式的html模板。 What am I missing? 我想念什么? I have seen some examples of returning excel files as a FileResult in MVC and they are not much different from mine. 我已经看到了一些在MVC中将excel文件作为FileResult返回的示例,它们与我的并没有太大区别。 Changing the MIME to 'application/vnd.ms-excel' didn't help either. 将MIME更改为“ application / vnd.ms-excel”也没有帮助。 Also, as far as I am aware, there is no need to implement any file download logic in the client, it should work as is, that is a response from the server. 而且,据我所知,不需要在客户端中实现任何文件下载逻辑,它应该按原样工作,即来自服务器的响应。 Will appreciate any hints on the subject. 将不胜感激关于该主题的任何提示。

PS: I know that in general I should not load an entire file into memory, but this is currently for testing purposes (I know an approximate limit to returned file sizes) and will most surely be changed in the future development. PS:我知道一般来说我不应该将整个文件加载到内存中,但这是出于测试目的(我知道返回文件大小的大约限制),并且在将来的开发中肯定会更改。

You should change 你应该改变

public ActionResult GetExcelFile(int id)

To

public FileResult GetExcelFile(int id)

And of course you can't handle Json response for FileResult . 当然,您不能处理FileResult的 Json响应。 It should be like that; 应该是这样

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
            }
}

You are not saving an xlsx file. 您没有保存xlsx文件。 You are saving an html file with xlsx extension. 您正在保存带有xlsx扩展名的html文件。

You probably adjusted a sample found on the internet, but the initial extension was xls. 您可能调整了在Internet上找到的样本,但最初的扩展名为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. 带有xls扩展名的html文件也不是Excel文件,但是MS Excel知道呈现html文件并将其显示到电子表格中。 Still, with the recently MS Excel version a warning is raised that is an invalid file format. 但是,对于最近的MS Excel版本,仍会发出警告,指出该文件格式无效。

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. 如果需要保存xlsx文件,则需要从Microsoft, EPPlus开源或EasyXLS商业版中搜索具有30天试用期的Excel库,例如OpenXML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM