【问题标题】:ClosedXML: Export To Excel not downloading the File MVC 4ClosedXML:导出到 Excel 不下载文件 MVC 4
【发布时间】:2016-02-09 12:41:01
【问题描述】:

我有一个List<T>,我将其转换为数据表,然后使用 ClosedXML 库通过Kingsoft-Spreadsheets 将该数据表导出到 Excel。

但是,由于某种原因,代码无法正常工作并且工作表没有被下载。我的 MVC 视图上出现奇怪的符号屏幕。我附上了图片以供参考。非常感谢任何帮助。

【问题讨论】:

    标签: c# asp.net-mvc export-to-excel closedxml kingsoft


    【解决方案1】:

    看起来 Excel 文件已正确创建,但您的浏览器尝试像纯文本文件一样打开它。正确设置响应的内容类型和内容处置标头,如下所示:

    Response.AddHeader("content-disposition", "attachment; filename=" + myName);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // or "application/vnd.ms-excel"
    

    有关完整的工作代码示例,请参阅此 question 及其答案。

    【讨论】:

    • 先生,我已经添加了上面的 contentType 和 AddHeader 值,尽管错误仍然存​​在。
    • DataTable dtq = GetDT(List); MemoryStream MyMemoryStream = new MemoryStream();使用 (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dtq);响应。清除(); Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=HelloWorld.xlsx");响应缓冲区=真; wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush();响应。结束(); }
    • 我尝试了不同的代码sn-ps;但没有成功,所有内容都呈现到浏览器,欢迎任何建议
    【解决方案2】:

    我的错,我在单击导出 Excel 按钮时使用 ajax 回发,没有页面回发。实际上需要整页回发。我刚刚添加了带有相应控制器和操作方法的 window.location.href,瞧……它工作正常。

    【讨论】:

      【解决方案3】:

      你应该避免调用 ajax :

      function ExportSPReport() {
          window.location = '@Url.Action("ExportSPReport", "Report")';
          @*$.ajax({
                  url: '@Url.Action("ExportSPReport", "Report")',
                  type: "GET",
                  success: function (data) {
                      //alert(data);
                      //$("#downloadFile").attr("href", data);
                      //document.getElementById('downloadFile').click();
                  },
                  error: function (reponse) {
                  }
              });
          }*@
      }
      

      【讨论】:

      • 不要使用ajax调用,使用窗口位置
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多