首页 > 解决方案 > WebAPI 2 导出在 IIS 7/8 上部署时损坏的 Excel、PDF,但在我的本地计算机上的 IIS 10 中正常工作

问题描述

WebAPI 2 导出在 IIS 7/8 上部署时损坏的 Excel、PDF,但在我的本地计算机上的 IIS 10 中正常工作。这是我打开时的excel文件在此处输入图像描述

这是我呈现excel的代码

[HttpPost]
    [Route("api/ThiSinhDuThi/ExportExcel")]
    public HttpResponseMessage ExportExcel()
    {

        string filepath = HttpContext.Current.Server.MapPath("~/Excel_Template/BieuDSTSDuThi.xls");
        //FileInfo template = new FileInfo(filepath);
        HSSFWorkbook hssfwb;
        using ( FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read) )
        {
            hssfwb = new HSSFWorkbook(file);
            file.Close();
        }
       
        using ( var memoryStream = new MemoryStream() ) //creating memoryStream
        {
            hssfwb.Write(memoryStream);
          
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(memoryStream.ToArray())
            };
            
            response.Content.Headers.ContentType = new MediaTypeHeaderValue
                   ("application/vnd.ms-excel");
            response.Content.Headers.ContentDisposition =
                   new ContentDispositionHeaderValue("attachment")
                   {
                       FileName = "DSThiSinhDuThi.xls"
                   };
            
            return response;
        }
        //return stream;


    }

标签: c#asp.netexceliisasp.net-web-api2

解决方案


对于 xls 来说,这似乎太人类可读了……也许它应该是 .xlsx 才能正确打开……尽管您可以将文件上传到某处进行检查?

或者,如果这是一个响应,它可能更多,然后尝试查看在 xls 文件中复制后在浏览器中不可见的附件部分是否有效......

我怀疑你得到的内容不应该直接从浏览器中使用,但可能是某些客户端应用程序,或者当它不应该在 IIS7/8 上进入 JSON 时它正在被序列化(即错误更有可能在上游Web 服务器设置在某些输出格式化程序中而不是在该代码中)?


推荐阅读