使用Ajax生成的Excel文件并下载的实例
时间:2020-10-07 14:25:48|栏目:JavaScript代码|点击: 次
很久?]有??文章啦,今天分享一??如何在ASP.NET MVC里使用Ajax下?d生成文件的方法,以下只是??人心得:
大家都???知道,在ASP.NET MVC里,如果通?^Ajax?{用后?_控制器?r,可以返回一??JSON?ο螅?但并不能直接返回文件(除非刷新?面,那就不是Ajax啦),所以如果想用Ajax生成文件并下?d的?,那只要?⑸?成的文件先保存到服?掌魃希?然後再?⑽募?路?酵ㄟ^JSON返回,之後才可以?M行下?d,??然由於是??r性存放,所以??下?d完后就需要?R上?h除相??的文件。
以下是做法以??B生成Excel?槔?(生成Excel的具?w步?E我就省略了,?@并不是此文章的重?c):
1. 首先??建Action生成Excel文件
[HttpPost]
public JsonResult ExportExcel()
{
DataTable dt = DataService.GetData();
var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
//?⑸?成的文件保存到服?掌鞯呐R?r目?里
string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
using (var exportData = new MemoryStream())
{
//如何生成Excel?@里就不???f明啦,我?@里??Excel的操作使用的是 NPOI
Utility.WriteDataTableToExcel(dt, ".xls", exportData);
FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
exportData.WriteTo(file);
file.Close();
}
var errorMessage = "you can return the errors in here!";
//返回生成的文件名
return Json(new { fileName = fileName, errorMessage = "" });
}
2. ??建下?d用的 Action
[HttpGet]
[DeleteFileAttribute] //Action Filter, 下?d完后自??h除文件,?@???傩陨葬峤忉?
public ActionResult Download(string file)
{
//到服?掌髋R?r文件目?下?d相??的文件
string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
//返回文件?ο螅??@里用的是Excel,所以文件?^使用了 "application/vnd.ms-excel"
return File(fullPath, "application/vnd.ms-excel", file);
}
3. 由於要做到下?d完后自??h除文件,所以再??建一?? Action Filter
public class DeleteFileAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Flush();
//???前filter context?D?Q成具?w操作的文件并?@取文件路??
string filePath = (filterContext.Result as FilePathResult).FileName;
//有文件路?胶缶涂梢灾苯?h除相?P文件了
System.IO.File.Delete(filePath);
}
}
4. 最后在前?_添加 Ajax ?{用的代?a:
//?@里我使用了 blockUI 做loading...
$.blockUI({ message: '<h3>Please wait a moment...</h3>' });
$.ajax({
type: "POST",
url: '@Url.Action("ExportExcel","YourController")', //?{用相??的controller/action
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (data) {
//console.log(data.result);
$.unblockUI();
//接收返回的文件路?剑?此文件?@?r已保存到服?掌魃狭?
if (data.fileName != "") {
//通?^?{用 window.location.href 直接跳?D到下?d action ?M行文件下?d操作
window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
}
});
5. 完!






