【问题标题】:Why the browser can't show an EPPlus spreadsheet?为什么浏览器不能显示 EPPlus 电子表格?
【发布时间】:2015-07-20 14:41:31
【问题描述】:

我尝试了很多选择,但完全不成功。我的需要是在服务器中创建一个电子表格,然后用户在 asp.net MVC 5 环境中的浏览器中获取它。

在服务器中的代码是:

[HttpPost]    
public ActionResult ExportToExcel([ModelBinder(typeof(DevExpressEditorsBinder))] Reports data)
    {
  ExcelPackage pck = new ExcelPackage();
  var ws = pck.Workbook.Worksheets.Add("Sample1");

  ws.Cells["A1"].Value = "Sample 1";
  ws.Cells["A1"].Style.Font.Bold = true;
  var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
  shape.SetPosition(50, 200);
  shape.SetSize(200, 100);
  shape.Text = "Sample 1 text text text";

  if (data.PDFFileName == null) data.PDFFileName = "Spreadsheet.xlsx";
  data.PDFFileName = Path.GetFileNameWithoutExtension(data.PDFFileName) + ".xlsx";

  FileContentResult result = new FileContentResult(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  result.FileDownloadName = data.PDFFileName;
  return result;
}

观点是

@Ajax.ActionLink("Created Spreadsheet", "ExportToExcel", "GraphReport", null, new AjaxOptions { HttpMethod = "POST" }, new { @class="btn btn-warning" })

Chrome 中的结果是:

Remote Address:[::1]:49711

Request URL:http://localhost:49711/GraphReport/ExportToExcel

Request Method:POST

Status Code:200 OK

Response Headers

Cache-Control:private, s-maxage=0

Content-Disposition:attachment; filename=Spreadsheet.xlsx

Content-Length:3561

Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Date:Mon, 29 Jun 2015 22:54:38 GMT

Server:Microsoft-IIS/8.0

X-AspNet-Version:4.0.30319

X-AspNetMvc-Version:5.2

X-Powered-By:ASP.NET

X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcbWNhc3Ryb1xEb2N1bWVudHNcVmlzdWFsIFN0dWRpbyAyMDEzXFByb2plY3RzXE1jU29mdFxDVlNcQmVlaGl2ZU1WQ1xHcmFwaFJlcG9ydFxFeHBvcnRUb0V4Y2Vs?=

Request Headers

Accept:*/*

Accept-Encoding:gzip, deflate

Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4

Connection:keep-alive

Content-Length:31

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

代码在响应中:

PKÓÝFCjkh'¬[Content_Types].xmlµÛN!_eíYh½0ÆtÛjb}f»¤ÂÐþ½,[ij¢I{5?3ß?f½5Õ#iï6åV¡^i·jØûò©¾e%p
wذ-æ³eª\ë¨a]JáNZ ´>ZHyW"\Ã

为什么它不被解释为下载附件?

【问题讨论】:

  • 什么也没发生。该操作被调用、处理并返回。返回的是所需的电子表格,但未处理新视图(电子表格下载)。 EPPlus 示例有效,因此浏览器可以理解 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。

标签: asp.net-mvc epplus


【解决方案1】:

这是因为您无法通过 AJAX 调用下载文件。

解决方法:创建一个表单,使用POST方法,提交表单。当服务器页面响应请求时,为文件的 mime 类型写一个响应头,它会出现一个下载对话框。如果服务器返回错误,您可能需要使用iframe 来防止您的网站导航到错误页面。

很多这样的问题,都有答案..

Ajax call to download file returned from RESTful service

Handle file download from ajax post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 2015-01-15
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多