2016-07-27 161 views
0

我有一個動態生成的HTML表格。我有一個ActionResult方法「GetOrders」,它返回一個基於用戶提供的日期範圍的OrderViewModel列表對象。渲染表後,我想有第二個操作方法,該數據導出到Excel文件。將HTML表格導出到Excel

我的問題是:我是否必須解析呈現到數據集/ gridview中的HTML表格,還是有辦法保存原始「GetOrders」操作方法中正在查詢的數據?這樣我就可以將它傳遞給第二個導出函數。

我提供了一些代碼,以幫助理解什麼,我試圖完成的..

[HttpPost] 
    public ActionResult GetOrders(DateTime startDate, DateTime endDate) 
    { 

     var model = db.SalesOrderDetails 
      .Where(e => e.SalesOrderHeader.OrderDate > startDate) 
      .Where(e => e.SalesOrderHeader.OrderDate < endDate) 
      .Join(db.Products, order => order.ProductID, 
       product => product.ProductID, 
       (order, product) => new OrderViewModel() 
       { 
        Quantity = order.OrderQty, 
        UnitNet = order.UnitPrice, 
        DueDate = order.SalesOrderHeader.DueDate, 
        CustomerPO = order.SalesOrderHeader.PurchaseOrderNumber, 
        InvoiceNumber = order.SalesOrderHeader.SalesOrderNumber, 
        InvoiceTotal = order.SalesOrderHeader.TotalDue, 
        OrderDate = order.SalesOrderHeader.OrderDate, 
        AccountNumber = order.SalesOrderHeader.AccountNumber, 
        Store = order.SalesOrderHeader.Customer.Store.Name, 
        Customer = order.SalesOrderHeader.Customer.Person.FirstName + " " + 
           order.SalesOrderHeader.Customer.Person.LastName, 
        ProductNumber = product.ProductNumber 
       }).Take(15); 

     return View(model.ToList()); 
    } 

有沒有一種方法來「搶」這個數據,並將其傳遞到第二exportToExcel功能?或者我需要弄清楚如何解析它?

回答

0

這是各種方法 讓一個你ActionMethod返回一個Json ,如:

[HttpPost] 
public JsonResult GetOrders(DateTime startDate, DateTime endDate) 
{ 
//your code 
return Json(model.toList(),JsonRequestBehavior.AllowGet); 
} 

。使一個Ajax調用GetOrders,如:

$.ajax({ 
      type: "POST", 
      url: '@Url.Action("GetOrders")', 
      dataType: "json", 
      data: { startDate: startDate, endDate: endDate, catid: catid, prdId: prdId, brandId: brandId }, 
      async: true, 
      success: function (data) { 
        var htmlhead = "<thead>  <tr><th style=\"width:6%; text-align:center;\"> Quantity</th> <th style=\"text-align:center;margin-left:4%;\">UnitNet</th><th style=\"text-align:center;margin-left:4%;\">DueDate</th></tr> </thead>"; 
       for (var i = 0; i < data.length; i++) { 
        htmlval = htmlval + ("<tr><td>" + data[i].Quantity + "</td><td style=\"text-align:center;\"> " + data[i].UnitNet + "</td><td style=\"text-align:center;\"> " + data[i].DueDate + "</td></tr>"); 
       } 
       html = htmlhead + htmlval; 
       $("#table").html(html); 
       window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=dvData]').html())); 
      }, 

      error: function (jqXHR, exception) { 
       console.log(jqXHR.responseText); 

      } 
     }); 

做創建名一個div 「dvdata」和表如:

<div id="dvData" style="display:none;"> 

<table id="table"></table> 

或者,假設你有HTML表格在你看來,你想下載Excel中的表,然後看到thisthis小提琴

或者您可以使用this插件