如何导出Asp.Net MVC脱颖而出? [英] How to export to excel in Asp.Net MVC?
本文介绍了如何导出Asp.Net MVC脱颖而出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SCRIPT
function PostExportValues(meter_id, range_type_id, start_date, end_date, returnUrl) {
var meter = $("#meter_selection").val()[0];
$.ajax({
url: '@Url.Action("GridExportToExcel", "Widget")',
type: 'POST',
data: { MeterType: meter_id, DateRangeType: range_type_id, StartDate: start_date, EndDate: end_date, returnUrl: returnUrl, Meter: meter },
success: function () {
alert("Success.");
},
error: function () {
alert("Error!");
}
}); //end ajax
} //end PostExportValues
控制器
public void GridExportToExcel(int MeterType, int DateRangeType, DateTime? StartDate, DateTime? EndDate, string returnUrl, int Meter)
{
Customers customer = CustomerManager.GetCustomer(WebSecurity.CurrentUserId);
//if start date is null, then set it to another early date.
DateTime startDate = DateTimeManager.GetStartDate(StartDate, DateRangeType, customer.sno);
//if end date is null, then set to date time now.
DateTime endDate = DateTimeManager.GetEndDate(EndDate, StartDate);
IQueryable<MeterReadingsForChart> meterReadings = MeterReadingManager.GetCustomerMeterReadings(customer.sno, MeterType, Meter, startDate, endDate, DateTimeManager.GetTimeIntervalTypeById(DateRangeType)).AsQueryable(); // MeterReadingManager.GetCustomerTotalMeterReadings(customer.sno, MeterType, startDate, endDate, DateTimeManager.GetTimeIntervalTypeById(DateRangeType)).AsQueryable();
var table = MeterReadingManager.GetMeterReadingsPivot(meterReadings, MeterType);
//table output some thing like following:
//T1 T2 T3
//10 20 25
//13 23 21
//15 26 27
var grid = new GridView();
grid.DataSource = table;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
//return View("Index");
}
方法 GridExportToExcel
工作和文字警示消息成功。
,但没有采取行动(没有任何反应)
Method GridExportToExcel
is working and script alert message is Success.
, but there is no action(nothing happens).
我在想什么?我希望Excel文件下载全自动。
What am I missing? I expect that excel file automaticly download.
谢谢...
推荐答案
您不能调用一个AJAX查询文件下载,因为浏览器不会触发文件下载。不使用你的控制器的方法Ajax调用,您可以像使用
You cant call a file download on a ajax query because the browser wont trigger the file download. dont use an ajax call to your controller method, you can use like
window.open("url/Exporttoexcel?id=");
与添加PARAMATERS。
with adding paramaters.
这篇关于如何导出Asp.Net MVC脱颖而出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文