2013-01-14 24 views
4

SCRIPT如何在Asp.Net MVC中导出为ex​​cel?

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工作和文字警示消息Success.,但没有采取行动(没有任何反应)。

我错过了什么?我期望excel文件自动下载。

谢谢...

+0

嗯而不调试它很难说,你使用萤火虫?如果没有下载它,看看你的发布数据发送了什么 –

+0

发送数据没有错误,它可能是关于请求的数据。控制器方法正在工作(我调试它)。预计还会恢复数据。我认为,问题是像@Steve那样的ajax调用 –

回答

9

你不能在ajax查询上调用文件下载,因为浏览器不会触发文件下载。不要使用ajax调用您的控制器方法,您可以使用像

window.open("url/Exporttoexcel?id="); 

添加参数。

+2

'window.open' :)。非常感谢... –

0

您也可以使用

window.location.href = "controllerName/GridExportToExcel?id="