如何为jqGrid启用excel导出按钮

时间:2011-04-02 22:32:01

标签: asp.net-mvc jqgrid export-to-excel

您好 我想在jqgrid的寻呼机中显示“export to excel”按钮。我尝试了很多方法,阅读了很多文章/帖子,但我没有看到这个按钮。文档也没有任何用处。我应该采取哪些措施来查看此按钮

聚苯乙烯。我使用ASP.NET MVC

PSS。我的代码是

<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>

但我没有看到excel导入按钮。 http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html

为什么?

3 个答案:

答案 0 :(得分:6)

假设

的标记
<table id="jqgrid"></table>
<div id="pager"></div> 

的内容
$('#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将是一个JavaScript函数,它将调用控制器操作来生成CSV文件。

这是 an example ,与jQuery flot结合使用。创建一些数据,选择一些网格行,然后单击网格左下角的生成图形按钮以绘制点。请注意,这在小于8的Internet Explorer中不起作用,因为它需要支持HTML 5 canvas元素(我并不打算包含excanvas)。

修改

您的标记无效,因为您需要初始化navGrid才能设置自定义按钮( see note on page )。你可以这样做

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();
}

答案 1 :(得分:1)

我所做的是在服务器上创建一个csv文件,并在我的视图中显示网格旁边的下载链接。

它不像你想象的那样光滑,但实现起来既快捷又简单。

从列表中创建csv文件的扩展方法(来自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());
    }

控制器:

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

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

            model.ErrorFullFileName = errorFilePath;

在视图中:

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

答案 2 :(得分:0)

我用过它并且效果很好

            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"
        });