ASP.net MVC正在下载Excel [英] ASP.net MVC Downloading Excel

查看:71
本文介绍了ASP.net MVC正在下载Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已设法使用HTMLTextwriter创建Excel文件,但返回的文件是Javascript函数。

I have managed to create the Excel file using HTMLTextwriter, but the returned file is into a Javascript function.

视图代码为:

<input type="submit" id = "exportExcelBtn" class = "searchButton" value="Export To Excel" 
onclick= "ExportToExcel();"/>

JS函数然后获取控制操作所需的数据,然后调用相关操作,如这样:

The JS function then gets the data required for the control action, and then calls the relevant action, as such:

$.ajax({
    type: "GET",
    url: "/Search/ExportToExcel",
    data: { //parameters        },
    error: function (error) {
        alert(error.responseText);
    },
    success: function (data) {
        alert("success");
        alert(data);
    }
});

通过派生自ActionResult创建Excel文件,并返回JS方法。创建的Excel文件将被写入浏览器:

The Excel file is created, by deriving from ActionResult, and returned back to the JS method. The created Excel file is written to the browser as such:

HttpContext context = HttpContext.Current;
            context.Response.Clear();

            context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            context.Response.Charset = "";

            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            context.Response.ContentType = contentType;
            context.Response.Write(content);
            context.Response.End();

如何将该文件下载到用户计算机?

How then can I get that file downloaded to the users computer?

我可以很容易地在模型方法中使用File.WriteAllText,但我觉得这是在欺骗MVC方法?

I can easily just use File.WriteAllText in the model method, but I feel that is cheating the MVC method?

推荐答案

您不能在模型中使用 File.WriteAllText

这会将其写入服务器。

You can't use File.WriteAllText in the model.
That will write it to the server.

您需要将位置设置为返回Excel文件内容的URL。

在MVC中执行此操作的正确方法是返回文件(内容,application / x-ms-excel,fileName )

You need to set the location to a URL that returns the contents of the Excel file.
The correct way to do that in MVC is to return File(content,"application/x-ms-excel", fileName)

这篇关于ASP.net MVC正在下载Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆