Search code examples
asp.net-mvc-5jqgridfree-jqgrid

Export To Excel filtered data with Free jqgrid 4.15.4 in MVC


I have a question regarding Export to Excel in free-jqgrid 4.15.4. I want to know how to use this resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]} into my Business Logic Method.

Just for more clarification, I've using OfficeOpenXml and if I don't use filtered resultset(aforementioned) it is working fine and I'm able to download file with full records in an excel sheet. But I'm not sure what to do or how to utilize the resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]}

If required I can share my controller and BL code.

I have added a fiddle which shows implementation of Export to Excel button in jqGrid pager.

Before coming to here, I've read and tried to understand from following questions:

1] jqgrid, export to excel (with current filter post data) in an asp.net-mvc site

2] Export jqgrid filtered data as excel or CSV

Here is the code :

$(function () {
"use strict";
var mydata = [
    { id: "10",  FirstName: "test", LastName: "TNT", Gender: "Male" },
     { id: "11",     FirstName: "test2",    LastName: "ADXC", Gender: "Male" },
     { id: "12",     FirstName: "test3",    LastName: "SDR", Gender: "Female" },
     { id: "13",     FirstName: "test4",    LastName: "234", Gender: "Male" },
     { id: "14",     FirstName: "test5",    LastName: "DAS", Gender: "Male" },
];
$("#list").jqGrid({
data: mydata,

    colNames: ['Id', 'First Name', 'Last Name', 'Gender'],
     colModel: [
        {
            label: "Id",
            name: 'Id',
            hidden: true,
            search: false,
        },
        {
            label: "FirstName",
            name: 'FirstName',
            searchoptions: {
                searchOperators: true,
                sopt: ['eq', 'ne', 'lt', 'le','ni', 'ew', 'en', 'cn', 'nc'],
            }, search: true,
        },
        {
            label: "LastName",
            name: 'LastName',
            searchoptions: {
                searchOperators: true,
                sopt: ['eq', 'ne', 'lt', 'ni', 'ew', 'en', 'cn', 'nc'],
            }, search: true,
        },

        {
            label: "Gender",
            name: 'Gender',
            search: true, edittype: 'select', editoptions: { value: 'Male:Male;Female:Female' }, stype: 'select',

        },
        ],
        onSelectRow: function (id) {
        if (id && id !== lastsel) {
            jQuery('#list').restoreRow(lastsel);
            jQuery('#list').editRow(id, true);
            lastsel = id;
        }
    },
    loadComplete: function (id) {
        if ($('#list').getGridParam('records') === 0) {

            //$('#grid tbody').html("<div style='padding:6px;background:#D8D8D8;'>No records found</div>");
        }
        else {
            var lastsel = 0;
            if (id && id !== lastsel) {
                jQuery('#list').restoreRow(lastsel);
                jQuery('#list').editRow(id, true);
                lastsel = id;
              }
            }
        },      
    loadonce: true,
    viewrecords: true,
    gridview: true,
    width: 'auto',
    height: '150px',    
    emptyrecords: "No records to display",
    iconSet:'fontAwesome',
    pager: true,
    jsonReader:
    {
        root: "rows",
        page: "page",
        total: "total",
        records: "records",
        repeatitems: false,
        Id: "Id"
    },

});
jQuery("#list").jqGrid("navButtonAdd", {
    caption: "",
    buttonicon: "fa-table",
    title: "Export To Excel",
    onClickButton: function (e) {
        var projectId = null;
        var isFilterAreUsed = $('#grid').jqGrid('getGridParam', 'search'),
           filters = $('#grid').jqGrid('getGridParam', 'postData').filters;   
        var Urls = "/UsersView/ExportToExcel_xlsxFormat?filters="+ encodeURIComponent(filters); //' + encodeURIComponent(filters);/
        if (totalRecordsCount > 0) {
            $.ajax({
                url: Urls,
                type: "POST",
                //contentType: "application/json; charset=utf-8",
                data: { "searchcriteria": filters, "projectId": projectId, "PageName": "MajorsView" },
                //datatype: "json",
                success: function (data) {
                    if (true) {
                        window.location = '/UsersView/SentFiletoClientMachine?file=' + data.filename;
                    }
                    else {
                        $("#resultDiv").html(data.errorMessage);
                        $("#resultDiv").addClass("text-danger");
                    }                       
                },
                error: function (ex) {
                    common.handleAjaxError(ex.status);                        
                }
            });
        }
        else {
            bootbox.alert("There are no rows to export in the Participant List")
            if (dialog) {
                dialog.modal('hide');
            }
        }
    }
});
});

https://jsfiddle.net/ap43xecs/10/


Solution

  • There are exist many option to solve the problem. The simplest one consist of sending ids of filtered rows to the server instead of sending filters parameter. Free jqGrid supports lastSelectedData parameter and thus you can use $('#grid').jqGrid('getGridParam', 'lastSelectedData') to get the array with items sorted and filtered corresponds to the current filter and sorting criteria. Every item of the returned array should contain Id property (or id property) which you can use on the server side to filter the data before exporting.

    The second option would be to implement server side filtering based on the filters parameter, which you send currently to the server. The old answer (see FilterObjectSet) provides an example of filtering in case of usage Entity Framework. By the way, the answer and another one contain code, which I used for exporting grid data to Excel using Open XML SDK. You can compare it with your existing code.

    In some situations it could be interesting to export grid data to Excel without writing any server code. The corresponding demo could be found in the issue and UPDATED part of the answer.