How to enable excel export button for jqGrid

老子叫甜甜 提交于 2019-12-21 06:24:17

问题


Hello I want to show "export to excel" button in the pager of jqgrid. I tried many ways, read many articles/posts, but I don't see this button. Documentation does not have anything useful too. Which actions should I do to see this button

Ps. I use ASP.NET MVC

PSS. my code is

<link href="../../Scripts/jquery.UI/css/redmond/jquery-ui-1.8.1.custom.css" rel="Stylesheet"
    type="text/css" />
<link href="../../Scripts/jquery.jqGrid/css/ui.jqgrid.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/i18n/grid.locale-ru.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery.jqGrid.min.js"></script>


<table id="EmployeeTable">
</table>
<div id="EmployeeTablePager">
</div>
<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery('#EmployeeTable').jqGrid({
            url: '/Employee/EmployeeData',
            datatype: "json",
            mtype: 'POST',
            jsonReader: {
                page: "page",
                total: "total",
                records: "records",
                root: "rows",
                repeatitems: false,
                id: ""
            },
            colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
            colModel: [
            { name: 'Id', width: 20 },
            { name: 'FirstName', width: 105 },
            { name: 'LastName', width: 100 },
            { name: 'Email', width: 150 },
            { name: 'Date', width: 150, formatter: ndateFormatter }
            ],
            pager: '#EmployeeTablePager',
            excel: true,
            viewrecords: true
        }).jqGrid('navButtonAdd',
        '#EmployeeTablePager',
        { caption: " Export to Excel ",
            buttonicon: "ui-icon-bookmark",
            onClickButton: genCSV, position: "last"
        });
    });
    function genCSV() {
        alert('a');
    }

    function ndateFormatter(cellval, opts, rwdat, _act) {

        var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
        var date = new Date();
        date.setTime(time);
        return date.toDateString();
    }

</script>

but I don't see the excel import button. http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html

why?


回答1:


Assuming markup of

<table id="jqgrid"></table>
<div id="pager"></div> 

Something along the lines of

$('#grid')
    .jqGrid({ 
             datatype: "clientSide", 
             height: 190, 
             colNames: headers, 
             colModel: model, 
             multiselect: true, 
             pager: '#pager',
             pgbuttons: false,
             pginput: false,
             caption: "Random Data",
             deselectAfterSort: false,
             width: 930
    }) 
    .jqGrid('navButtonAdd', 
            '#pager',
            {caption:" Export to Excel ", 
            buttonicon:"ui-icon-bookmark", 
            onClickButton: genCSV, position:"last"});

genCSV will be a JavaScript function that will make the call to the controller action to generate a CSV file.

Here's an example, in combination with jQuery flot. Create some data, select some grid rows and then click the generate graph button in the bottom left of the grid to plot the points. Note that this will not work in Internet Explorer less than 8 as it requires support for the HTML 5 canvas element (and I haven't bothered to include excanvas).

EDIT:

Your markup is not working because you need to initialize a navGrid before being able to set a custom button (see note on page). You can do this like so

jQuery(document).ready(function () {
    jQuery('#EmployeeTable').jqGrid({
        url: '/Employee/EmployeeData',
        datatype: "json",
        mtype: 'POST',
        jsonReader: {
            page: "page",
            total: "total",
            records: "records",
            root: "rows",
            repeatitems: false,
            id: ""
        },
        colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
        colModel: [
        { name: 'Id', width: 20 },
        { name: 'FirstName', width: 105 },
        { name: 'LastName', width: 100 },
        { name: 'Email', width: 150 },
        { name: 'Date', width: 150, formatter: ndateFormatter }
        ],
        pager: '#EmployeeTablePager',
        excel: true,
        viewrecords: true
    })
      /* Need to initialize navGird before being able to set any custom buttons */
      .jqGrid('navGrid', '#EmployeeTablePager', {
        add: false,
        edit: false,
        del: false,
        search: false,
        refresh: false
    }).jqGrid('navButtonAdd',
    '#EmployeeTablePager',
    { caption: " Export to Excel ",
        buttonicon: "ui-icon-bookmark",
        onClickButton: genCSV, position: "last"
    });
});
function genCSV() {
    alert('a');
}

function ndateFormatter(cellval, opts, rwdat, _act) {

    var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
    var date = new Date();
    date.setTime(time);
    return date.toDateString();
}



回答2:


What I did was to create a csv file on the server and display a download link next to the grid in my view.

It's not as slick as what you have in mind but it is quick and easy to implement.

Extension method to create a csv file from a list (from another post on SO):

    public static string AsCsv<T>(this IEnumerable<T> items)
                                     where T : class
    {
        var csvBuilder = new StringBuilder();
        var properties = typeof(T).GetProperties();
        foreach (T item in items)
        {
            //string line = properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray().Join(",");
            string line= string.Join(", ", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
            csvBuilder.AppendLine(line);
        }
        return csvBuilder.ToString();
    }

    private static string ToCsvValue<T>(this T item)
    {
        if (item is string)
        {
            return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
        }
        double dummy;
        if (double.TryParse(item.ToString(), out dummy))
        {
            return string.Format("{0}", item.ToString());
        }
        return string.Format("\"{0}\"", item.ToString());
    }

Controller:

            model.AListOfData.ToArray().AsCsv();

            using (StreamWriter sw = System.IO.File.CreateText(errorFilePath))
            {
                sw.Write(values);
            }

            model.ErrorFullFileName = errorFilePath;

In the view:

<%=Html.ImageLink("", "AssetUpload", "DownloadErrors", "/?filename=" + Model.ErrorFullFileName, "/Content/Icons/excel.png", "Download errors and warnings", "imagelink")%>



回答3:


I used this and it works pretty well

            jQuery("#table_resultats").jqGrid('navGrid', "#yourpager").jqGrid( //#pager
            'navButtonAdd', "#yourpager", {
            caption : "Excel export",
            buttonicon : "ui-icon-arrowthickstop-1-s",
            onClickButton : null,
            position : "first",
            title : Excel export,
            cursor : "pointer"
        });


来源:https://stackoverflow.com/questions/5526331/how-to-enable-excel-export-button-for-jqgrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!