使用Kendo Grid自动导出到Excel

时间:2015-12-12 20:17:03

标签: asp.net-mvc excel kendo-grid

我有一个asp.net MVC5项目,我使用Kendo Grid来显示表数据并为用户提供Export-to-Excel功能。这些数据集的列数相对较小。例如大多是3-6列。但是,我有一些持怀疑态度的用户希望能够看到数据提供给某些Kendo图表,其中数据集比我想要放在视图/浏览器中的网格中的数据集大。

我的问题是,是否有人想出了一种方法来利用“导出到Excel”功能,该功能是网格的一部分而不显示网格。我喜欢“导出”用于将数据推送到Excel的所有附加功能,所以我想知道这是否可行而不是将我自己的输出滚动到可以由Excel打开的csv文件。

想知道是否有办法直接从Controller使用Export-to-Excel功能,以便在Excel中将数据提供给用户?

这是Telerik的一个例子;

查看网格小部件

<script src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>

@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()    
.Name("grid")    
.HtmlAttributes( new { style = "width: 900px" } )
.Columns(columns => {
    columns.Bound(p => p.ProductName).Width(300).Locked()
           .ClientFooterTemplate("Total Count: #=count#")
           .ClientGroupFooterTemplate("Count: #=count#");
    columns.Bound(p => p.UnitPrice).Width(300);
    columns.Bound(p => p.UnitsOnOrder).Width(300)
           .ClientFooterTemplate("Average: #=average#")
           .ClientGroupFooterTemplate("Average: #=average#");
    columns.Bound(p => p.UnitsInStock).Width(300)
           .ClientFooterTemplate("Min: #= min # Max: #= max #")
           .ClientGroupHeaderTemplate("Units In Stock: #= value # (Count: #= count#)");
})
.ToolBar(tools => tools.Excel())
.Pageable()
.Sortable()
.Scrollable()
.Groupable()
.Excel(excel => excel
    .FileName("Kendo UI Grid Export.xlsx")
    .Filterable(true)
    .ProxyURL(Url.Action("Excel_Export_Save", "Grid"))
)
.Reorderable(r => r.Columns(true))
.Resizable(r => r.Columns(true))
.ColumnMenu()
.DataSource(dataSource => dataSource
    .Ajax()                 
    .PageSize(7)
    .Group(g => g.Add(p => p.UnitsInStock))
    .Aggregates(aggregates =>
    {
         aggregates.Add(p => p.UnitsInStock).Min().Max().Count();
            aggregates.Add(p => p.UnitsOnOrder).Average();
            aggregates.Add(p => p.ProductName).Count();
            aggregates.Add(p => p.UnitPrice).Sum();
    })
    .Read(read => read.Action("Excel_Export_Read", "Grid"))
)
)

CONTROLLER

using System.Collections.Generic;
using System.Web.Mvc;
using Kendo.Mvc.Examples.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System.Linq;
using System;

namespace Kendo.Mvc.Examples.Controllers
{
public partial class GridController : Controller
{
    public ActionResult Excel_Export()
    {
        return View();
    }

    public ActionResult Excel_Export_Read([DataSourceRequest]DataSourceRequest request)
    {
        return Json(productService.Read().ToDataSourceResult(request));
    }

    [HttpPost]
    public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
    {
        var fileContents = Convert.FromBase64String(base64);

        return File(fileContents, contentType, fileName);
    }
}
}

SERVICE

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Kendo.Mvc.Examples.Models
{
public class ProductService : IDisposable
{
    private SampleEntities entities;

    public ProductService(SampleEntities entities)
    {
        this.entities = entities;
    }

    public IEnumerable<ProductViewModel> Read()
    {
        return entities.Products.Select(product => new ProductViewModel
        {
             ProductID = product.ProductID,
             ProductName = product.ProductName,
             UnitPrice = product.UnitPrice.HasValue ? product.UnitPrice.Value : default(decimal),
             UnitsInStock = product.UnitsInStock.HasValue ? product.UnitsInStock.Value : default(short),
             QuantityPerUnit = product.QuantityPerUnit,
             Discontinued = product.Discontinued,
             UnitsOnOrder = product.UnitsOnOrder.HasValue ? (int)product.UnitsOnOrder.Value : default(int),
             CategoryID = product.CategoryID,
             Category = new CategoryViewModel()
             {
                 CategoryID = product.Category.CategoryID,
                 CategoryName = product.Category.CategoryName
             },
             LastSupply = DateTime.Today
        });
    }

    public void Create(ProductViewModel product)
    {
        var entity = new Product();

        entity.ProductName = product.ProductName;
        entity.UnitPrice = product.UnitPrice;
        entity.UnitsInStock = (short)product.UnitsInStock;
        entity.Discontinued = product.Discontinued;
        entity.CategoryID = product.CategoryID;

        if (entity.CategoryID == null)
        {
            entity.CategoryID = 1;
        }

        if (product.Category != null)
        {
            entity.CategoryID = product.Category.CategoryID;
        }

        entities.Products.Add(entity);
        entities.SaveChanges();

        product.ProductID = entity.ProductID;
    }

    public void Update(ProductViewModel product)
    {
        var entity = new Product();

        entity.ProductID = product.ProductID;
        entity.ProductName = product.ProductName;
        entity.UnitPrice = product.UnitPrice;
        entity.UnitsInStock = (short)product.UnitsInStock;
        entity.Discontinued = product.Discontinued;
        entity.CategoryID = product.CategoryID;

        if (product.Category != null)
        {
            entity.CategoryID = product.Category.CategoryID;
        }

        entities.Products.Attach(entity);
        entities.Entry(entity).State = EntityState.Modified;
        entities.SaveChanges();
    }

    public void Destroy(ProductViewModel product)
    {
        var entity = new Product();

        entity.ProductID = product.ProductID;

        entities.Products.Attach(entity);

        entities.Products.Remove(entity);

        var orderDetails = entities.Order_Details.Where(pd => pd.ProductID == entity.ProductID);

        foreach (var orderDetail in orderDetails)
        {
            entities.Order_Details.Remove(orderDetail);
        }

        entities.SaveChanges();
    }

    public void Dispose()
    {
        entities.Dispose();
    }
}
}

链接:http://demos.telerik.com/aspnet-mvc/grid/excel-export

BTW,这种'分类'是什么类型的架构?我喜欢它,并希望阅读它。

2 个答案:

答案 0 :(得分:1)

如何隐藏网格并添加自己的按钮(或类似按钮)来触发导出?

例如(使用引用的代码):

  1. 添加按钮(或在图表中添加类似的挂钩)

      <button id="myexport">Export to Excel</button>
    
  2. 隐藏网格并附加处理程序:

    $(document).ready(function () {
        $("#grid").hide();
    
        $("#myexport").click(function () {
            var grid = $("#grid").data("kendoGrid");
            grid.saveAsExcel();
        });
    });
    

答案 1 :(得分:0)

您示例中的架构是 ASP.NET MVC。

另一种方法是在点击页面上的某些内容时使用 jQuery 触发查找,例如带有 <div>id="export"

$('#export').click(function (e) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: 'Grid/Excel_Export_Save',
        async: false,
        success: exportCSV,
    });
});

您可以编写自己的导出函数。我们有一种导出到 CSV 的方法,如下所示:

function exportCSV(json) {
    var csv = 'Product ID,Name,Unit Price,Qty In Stock,Discontinued,Category ID\n';
    var download = 'products.csv';
    $.each(json.Data, function (index, rowArray) {
        var row = [];
        row.push(rowArray.ProductID);
        row.push(rowArray.ProductName);
        row.push(rowArray.UnitPrice);
        row.push(rowArray.UnitsInStock);
        row.push(rowArray.Discontinued);
        row.push(rowArray.CategoryID);
        csv += row.join(',') + '\r\n';
    });
    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = download;
    hiddenElement.click();
};

要调用它,您需要在控制器中创建一个允许 Json 请求的函数:

public async Task<JsonResult> GetGapReport([DataSourceRequest] DataSourceRequest request, String serviceType = null) {
    var result = new DataSourceResult();
    var products = new List<ProductViewModel>();
    try {
        var report = await productService.Read();
        products.AddRange(report.ToArray());
        result = products.ToDataSourceResult(request);
    } catch (Exception err) {
        result.Errors = err.Message;
    }
    return new JsonResult {
      Data = result, 
      JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
      MaxJsonLength = Int32.MaxValue 
    };
}