【问题标题】:How to export the jqgrid's filtered contents to excel?如何将jqgrid的过滤内容导出到excel?
【发布时间】:2011-07-12 11:11:31
【问题描述】:

This 正是我想要的。我想在 jqgrid 的寻呼机中显示“导出到 excel”按钮,这将导出当前数据集(基于当前过滤器)。

但是在 Grails 中。请提出如何实现它。

我正在尝试以this 的方式。

【问题讨论】:

  • 您在服务器端使用什么操作系统(Windows 与否)和技术(.NET 与否)?能否在服务器上使用Open XML SDK 2.0 很重要。你用的是商业版的jqGrid吗(你参考了商业版jqGrid的一个例子)?
  • @Oleg:这是一个基于 java 的 GRAILS 应用程序,将部署在 Tomcat 中。我没有使用商业版。
  • 如果您使用 jqGrid 的开放免费版本,那么this demo 将无济于事。我不使用 GRAILS,所以在您不回答我的直接问题之前,它什么也没说,无论您是否可以使用 Open XML SDK 2.0。在专业环境中不能使用 CSV 数据而不是 Excel 文件的创建,因为用户在导入数据后必须进行太多的格式化和数据转换。这是我的看法。

标签: jquery grails jqgrid export-to-excel


【解决方案1】:

JQGrid 类提供了 ExportToExcel 函数,您可以使用该函数将网格内容导出到 excel。

您可以使用 JQGridState 类在导出时维护网格的当前状态(在分页、过滤、排序等之后)。您还可以指定是否只导出当前页面,所有整个数据源。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using JQGridMVCExamples.Models;
    using Trirand.Web.Mvc;

    namespace JQGridMVCExamples.Controllers.Grid
{
public partial class GridController : Controller
{
    // This is the default action for the View. Use it to setup your grid Model.
    public ActionResult FunctionalityExportExcel()
    {
        // Get the model (setup) of the grid defined in the /Models folder.
        var gridModel = new OrdersJqGridModel();
        var ordersGrid = gridModel.OrdersGrid;

        // Setting the DataUrl to an action (method) in the controller is required.
        // This action will return the data needed by the grid
        ordersGrid.DataUrl = Url.Action("ExcelGridDataRequested");

        // customize the default Orders grid model with custom settings
        // NOTE: you need to call this method in the action that fetches the data as well,
        // so that the models match
        SetExportGrid(ordersGrid);

        // Pass the custmomized grid model to the View
        return View(gridModel);
    }

    // This method is called when the grid requests data        
    public JsonResult ExcelGridDataRequested()
    {
        // Get both the grid Model and the data Model
        // The data model in our case is an autogenerated linq2sql database based on Northwind.
        var gridModel = new OrdersJqGridModel();
        var northWindModel = new NorthwindDataContext();

        // customize the default Orders grid model with our custom settings
        SetExportGrid(gridModel.OrdersGrid);

        // Save the current grid state in Session
        // We will later need it for Excel Export
        JQGridState gridState = gridModel.OrdersGrid.GetState();
        Session["gridState"] = gridState;

        // return the result of the DataBind method, passing the datasource as a parameter
        // jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc

        return gridModel.OrdersGrid.DataBind(northWindModel.Orders);
    }

    public JsonResult ExcelExport_AutoCompleteShipName(string term)
    {
        var northWindModel = new NorthwindDataContext();
        JQAutoComplete autoComplete = new JQAutoComplete();

        autoComplete.DataField = "ShipName";
        autoComplete.AutoCompleteMode = AutoCompleteMode.BeginsWith;
        autoComplete.DataSource = from o in northWindModel.Orders
                                  select o;
        return autoComplete.DataBind();
    }

    private void SetExportGrid(JQGrid ordersGrid)
    {
        // show the search toolbar
        ordersGrid.ToolBarSettings.ShowSearchToolBar = true;
        ordersGrid.ToolBarSettings.ShowSearchButton = true;

        var orderDateColumn = ordersGrid.Columns.Find(c => c.DataField == "OrderDate");
        orderDateColumn.DataFormatString = "{0:yyyy/MM/dd}";
        orderDateColumn.SearchType = SearchType.DatePicker;
        orderDateColumn.DataType = typeof(DateTime);
        orderDateColumn.SearchControlID = "DatePicker";
        orderDateColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;

        var shipNameColumn = ordersGrid.Columns.Find(c => c.DataField == "ShipName");
        shipNameColumn.SearchType = SearchType.AutoComplete;
        shipNameColumn.DataType = typeof(string);
        shipNameColumn.SearchControlID = "AutoComplete";
        shipNameColumn.SearchToolBarOperation = SearchOperation.Contains;

        var orderIDColumns = ordersGrid.Columns.Find(c => c.DataField == "OrderID");
        orderIDColumns.Searchable = true;
        orderIDColumns.DataType = typeof(int);
        orderIDColumns.SearchToolBarOperation = SearchOperation.IsEqualTo;

        SetCustomerIDSearchDropDown(ordersGrid);
        SetFreightSearchDropDown(ordersGrid);
    }

    private void SetCustomerIDSearchDropDown(JQGrid ordersGrid)
    {
        // setup the grid search criteria for the columns
        JQGridColumn customersColumn = ordersGrid.Columns.Find(c => c.DataField == "CustomerID");
        customersColumn.Searchable = true;

        // DataType must be set in order to use searching
        customersColumn.DataType = typeof(string);
        customersColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
        customersColumn.SearchType = SearchType.DropDown;

        // Populate the search dropdown only on initial request, in order to optimize performance
        if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
        {
            var northWindModel = new NorthwindDataContext();
            var searchList = from customers in northWindModel.Customers
                             select new SelectListItem
                             {
                                 Text = customers.CustomerID,
                                 Value = customers.CustomerID
                             };

            customersColumn.SearchList = searchList.ToList();
            customersColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
        }
    }

    private void SetFreightSearchDropDown(JQGrid ordersGrid)
    {
        // setup the grid search criteria for the columns
        JQGridColumn freightColumn = ordersGrid.Columns.Find(c => c.DataField == "Freight");
        freightColumn.Searchable = true;

        // DataType must be set in order to use searching
        freightColumn.DataType = typeof(decimal);
        freightColumn.SearchToolBarOperation = SearchOperation.IsGreaterOrEqualTo;
        freightColumn.SearchType = SearchType.DropDown;

        // Populate the search dropdown only on initial request, in order to optimize performance
        if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
        {
            List searchList = new List();
            searchList.Add(new SelectListItem { Text = "> 10", Value = "10" });
            searchList.Add(new SelectListItem { Text = "> 30", Value = "30" });
            searchList.Add(new SelectListItem { Text = "> 50", Value = "50" });
            searchList.Add(new SelectListItem { Text = "> 100", Value = "100" });

            freightColumn.SearchList = searchList.ToList();
            freightColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
        }
    }

    public ActionResult ExportToExcel(string exportType)
    {

        var gridModel = new OrdersJqGridModel();
        var northWindModel = new NorthwindDataContext();
        var grid = gridModel.OrdersGrid;

        // Get the last grid state the we saved before in Session in the DataRequested action
        JQGridState gridState = Session["GridState"] as JQGridState;

        // Need to set grid options again
        SetExportGrid(grid);

        if (String.IsNullOrEmpty(exportType))
            exportType = "1";

        switch (exportType)
        {
            case "1":
                grid.ExportToExcel(northWindModel.Orders);
                break;
            case "2":
                gridState.CurrentPageOnly = false;
                grid.ExportToExcel(northWindModel.Orders, gridState);
                break;
            case "3":
                gridState.CurrentPageOnly = true;
                grid.ExportToExcel(northWindModel.Orders, gridState);
                break;
        }


        return View();
    }
}
}

【讨论】:

  • 仅供参考,问题是关于 Grails 开发的,它只支持 Groovy 或 Java 代码。上面的类似乎是 C#
【解决方案2】:

执行此操作的最简单方法实际上是将数据呈现为直接的 HTML 表格,然后使用 content-type 告诉浏览器在 Excel 中打开它。你总是可以使用更复杂的东西,比如 Apache POI,来生成一个真正的电子表格,但除非你需要公式,否则真的没有意义。

所以最简单的方法就是使用没有复杂布局的视图。 http://support.microsoft.com/kb/271572 有一个 VBScript 示例,它的可读性足以让您轻松将其适应 Grails/GSP。请注意,对于数据,一个包含表格的简单 HTML 响应似乎就足够了,我们在实践中从来不需要嵌入的 Excel 特定命名空间的东西。

您需要的 MIME 类型在这里得到回答:Setting mime type for excel document,并且接受的答案中的标题显示了如何将数据传递到 Excel。附件的内容配置可能是您下载数据所需要的。

即使下载到一个实际包含 HTML 的 .xls 文件,当您打开该文件时,Excel 似乎仍然会做正确的事情。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多