开发者

jqgrid/mvc 3 - Export to excel and raise a file download dialog?

I have read many solutions but I haven't got the working one yet.

My problem is quite easy, export data to excel file and raise a file download dialog.

However the file download dialog doesn't show. I could be the call method from View to Controller is wrong, because I debugged to ExportToExcel function and there's no error

Thank in advance

This is View:

<script type="text/javascript">
    $(document).ready(function () {
        jQuery("#list").jqGrid({
            url: '/documents/List',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['ID', 'File Name', 'Description', 'File', 'Modified', 'File Type', 'Access'],
            colModel: [
                    { name: 'ID', index: 'id', width: 40, align: 'left', key: true, editable: false, editrules: { edithidden: false }, edittype: 'text' },
                    { name: 'FileName', index: 'filename', width: 315, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                    { name: 'Description', index: 'description', width: 210, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} },
                    { name: 'File', index: 'file', hidden: true, enctype: "multipart/form-data", method: "post", editable: true, edittype: 'file', editrules: { edithidden: true, required: true }, formoptions: { elmsuffix: ' *'} },
                    { name: 'Modified', index: 'modified', width: 105, align: 'left', editable: false, edittype: 'text', editoptions: { size: 20, dataInit: function (el) { $(el).datepicker({ dateFormat: 'mm/dd/yy' }); } } },
                    { name: 'FileType', index: 'filetype', width: 210, align: 'left', editable: true, edittype: 'select', editrules: { required: true }, formoptions: { elmsuffix: ' *' },
                        editoptions: { dataUrl: '/HtmlSelectHelper/ConstructDocumentTypeList' }
                    },
                    { name: 'Access', index: 'access', width: 114, align: 'left', editable: true, edittype: 'select', editrules: { required: true }, formoptions: { elmsuffix: ' *' },
                        editoptions: { value: '0:Private;1:Public' }
                    },
               ],
            autowidth: false,
            forceFit: false,
            shrinkToFit: false,
            width: 1024,
            height: 600,
            rowNum: 10,
            rowList: [5, 10, 20, 50, 100],
            pager: jQuery('#pager'),
            sortorder: "desc",
            sortable: true,
            viewrecords: true,
            caption: "Documents List",
            editurl: "/documents/edit"
        });
        jQuery("#list").jqGrid('navGrid', '#pager',
        {
            add: true, edit: true, view: true, del: true
        },
        {
            closeAfterEdit: tr开发者_StackOverflowue,
            closeAfterAdd: true,
            width: 400
        },
        {
            closeAfterEdit: true,
            closeAfterAdd: true,
            width: 400,
            serializeEditData: function (data) { return $.param($.extend({}, data, { id: 0 })); }
        },
        {
    },
        {
            multipleSearch: true
        });

    jQuery("#list").jqGrid('navButtonAdd', '#pager', { caption: "", buttonicon: "ui-icon-calculator", title: "choose columns",
        onClickButton: function () {
            jQuery("#list").jqGrid('columnChooser');
        }
    });

    jQuery("#list").jqGrid('navButtonAdd', '#pager', {
        caption: "", buttonicon: "ui-icon-print", title: "Excel Export",
        onClickButton: function () {
                        $.post("/Documents/ExportToExcel", {}, function () {

                        });
        }
    });

    jQuery("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
});               
</script>

This is Controller:

public ActionResult ExportToExcel()
{
    var documents = db.documents as IEnumerable<document>;

    var grid = new GridView
                   {
                       DataSource = from document in documents
                                    select new
                                               {
                                                   filename = document.filename,
                                                   description = document.description,
                                                   modified = document.modified.ToString(),
                                                   filetype = document.filetype,
                                                   access = document.access
                                               }
                   };

    grid.DataBind();

    Response.ClearContent();
    Response.AddHeader("content-disposition", "inline; filename=Excel.xls");

    Response.ContentType = "application/excel";

    StringWriter sw = new StringWriter();

    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    Response.Write(sw.ToString());

    Response.End();
    return View("Index");
}


I had the same problem and managed to solve by changing the view as follows:

jQuery("#list").jqGrid('navButtonAdd', '#pager', {
    caption: "", buttonicon: "ui-icon-print", title: "Excel Export",
    onClickButton: function () {
                    window.location.href = "/Documents/ExportToExcel";
    }
});


Please change the code as below

Instead of returning View() return new EmptyResult();

also Response.ContentType="application/vnd.ms-excel"

If your code is not working, you can use NPOI for Excel file manipulation


Don't render the view at all.

Instead of returning View() return File() passing byte[] with file content. More info here: http://msdn.microsoft.com/en-us/library/dd460208.aspx


i think the best way is to use the FileResult

    public FileResult Binary(MyModel Model)
    {
        return new FileContentResult(bindata, "application/vnd.ms-excel")
                    {
                        FileDownloadName = "mytestfile.xls"
                    };        
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜