简体   繁体   English

ClosedXML:导出到Excel不下载文件MVC 4

[英]ClosedXML: Export To Excel not downloading the File MVC 4

I have a List<T> , which I convert to a Datatable and then export that Datatable to Excel via Kingsoft-Spreadsheets using ClosedXML library. 我有一个List<T> ,我将其转换为Datatable,然后使用ClosedXML库通过Kingsoft-Spreadsheets将Datatable导出到Excel。

However, for some reason the code is not working and the sheet is not getting downloaded. 但是,由于某种原因,代码无法正常工作,并且未下载工作表。 I am getting strange symbolic screen on my MVC view. 我的MVC视图上有一个奇怪的符号屏幕。 I have attached the image for reference. 我已附上图片以供参考。 Any help much appreciated. 任何帮助非常感谢。

在此输入图像描述

It looks like the Excel file is created correctly but your browser tries to open it like a plain text file. 看起来Excel文件已正确创建,但您的浏览器尝试将其打开,就像纯文本文件一样。 Set the content type and the content disposition header for the response correctly like this: 正确设置响应的内容类型和内容处置标头,如下所示:

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

For a full working code example see this question and its answers. 有关完整的代码示例,请参阅此问题及其答案。

My bad, I was using ajax post back on Export Excel button click,there was no page postback.Acutally full page post back is required. 我的不好,我正在使用ajax帖子返回导出Excel按钮点击,没有页面回发。需要回复整页回发。 I just added window.location.href with respective controller and action method and voila..its working fine. 我刚刚添加了window.location.href和各自的控制器和动作方法,并且工作正常。

You should avoid to call ajax : 你应该避免调用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) {
            }
        });
    }*@
}

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

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