user2934518
user2934518

Reputation: 1

Export to Excel from jqxgrid

Here' the part of my code.When i click one button and then download to excel a file with this jqxgrid. I've tried to find the answer on jqwidget.com, but that site was shutdown.
and i found some similar answer on this site. but it was about php. but mine is java.

$("#jqxgrid").jqxGrid(
{
    width: '99.7%',
    height: '99.7%',   
    source: dataAdapter,
    virtualmode: true,
    rendergridrows: function()
    {
        return dataAdapter.records;     
    },              
    theme: theme,
    columnsresize: true,    
    pageable: true,         
    enabletooltips: true,
    //autoheight: true,     
    //autorowheight: true,
    selectionmode: 'singlecell',    
    altrows: true,
    sortable: true, 
    editable: true,
    editmode: 'dblclick',
    scrollmode: 'deferred',
    pagesize: 30,
    pagesizeoptions: ['10', '20','30', '50', '100', '200', '300', '500'],
    columns: [
        { text: ' ',       datafield: 'procImg', align : 'center', cellsalign : 'center', width: '30px', cellsrenderer: imagerenderer, editable: false, filterable:false, sortable: false },
        (retireFlag=="0")?{ text: 'delete',    datafield: 'delBool', align : 'center', cellsalign : 'center', columntype: 'checkbox', width: '41px', filterable:false, sortable: false}:null,
        (retireFlag=="0")?{ text: 'Use', dataField: 'useBool',  align : 'center', cellsalign : 'center', columntype: 'checkbox', width: '67px',  editable: true, sortable: false}:null,                 
        { text: 'ID',      dataField: 'mng_id',  align : 'center', cellsalign : 'center', columntype: 'textbox',  width: '115px', editable: false, cellsrenderer: cellsrenderer1 },
    ]
});

Upvotes: 0

Views: 9471

Answers (2)

Systematix Infotech
Systematix Infotech

Reputation: 2365

In JQgrid you can follow this:

First create a button:

Download

 function Export() {
            var params = { "fromDate": $("#hdnFrom").val(), "toDate": $("#hdnTo").val() }
            var str = jQuery.param(params);
            window.open("/Analytics/ExportGridView?" + str, '_blank')
        }

Now call the handler method from controller:

public ActionResult ExportGridView(string fromDate,string toDate)
        {
            try
            {
                //LINQ to SQL context class

                //Create gridview object - Make sure you have added reference to Syster.Web.UI.ServerControls
                GridView gv = new GridView();
                //Call Method to apply style to gridview - This is optional part and can be avoided
                StyleGrid(ref gv);
                //assing datasource from context class to gridview object

                    gv.DataSource = GetReportDetails(fromDate, toDate);

                //gv.DataSource = Convert.(dataContext.GetTractorTrasactionDateReport);
                //Important - bind gridview object
                gv.DataBind();
                //We have gridview object ready in memory. Follow normal "export gridview to excel" code
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=AnalyticReport.xls");
                Response.ContentType = "application/ms-excel";
                //Ccreate string writer object and pass it to HtmlTextWriter object
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                //Call gridiview objects RenderControl method to output gridview content to HtmlTextWriter
                gv.RenderControl(htw);
                //Pass rendered string to Response object which would be presented to user for download
                Response.Write(sw.ToString());
                Response.End();
                return View("Analytics");
            }
            catch (Exception ex)
            {

                return Json(ex.Message.ToString());
            }

        }

Pass search filter from hidden fields:

public List<ExportModel> GetReportDetails(string fromDate, string toDate)
        {

            var userList = new List<ExportModel>();

            var Process = from TT in db.tblManagePosts
                          where TT.Date >= Convert.ToDateTime(fromDate) && TT.Date <= Convert.ToDateTime(toDate) && TT.IsArchive == 0
                          orderby TT.PostId descending
                          select new { TT.Title,TT.Content, TT.Date,TT.Views };

            int Count = Process.Count();
            if (Count > 0)
            {
                foreach (var selection in Process)
                {

                    ExportModel user = new ExportModel();
                    user.Title = selection.Title;
                    user.Content = Regex.Replace(selection.Content, @"<[^>]*>", String.Empty);
                    DateTime time = selection.Date;
                    String format = "dd/MM/yyyy";
                    user.Date = time.ToString(format);
                    user.Views = selection.Views;
                    userList.Add(user);

                }

            }
            return userList;
        }

You will get the correct search data in excel sheet.

Upvotes: 0

Ousmane
Ousmane

Reputation: 11

For the export to excel, you can use a button like this

<button id="export_Excel">Excel</button>
 and in your javascript file, 

    $("#export_Excel").click(function() {
        $("#jqxgrid").jqxGrid('exportdata', 'xls', 'Filename');
    });

This method will export the filtered content of your grid. The "exportdata" method have one last argument. See documentation below

Exports all rows loaded within the Grid to Excel, XML, CSV, TSV, HTML or JSON.

The first parameter of the export method determines the export's type - 'xls', 'xml', 'html', 'json', 'tsv' or 'csv'. The second parameter is the file's name. If you don't provide a file name, the Grid will export the data to a local variable. For example:

var data = $("#jqxgrid").jqxGrid('exportdata', 'json');

The third parameter is optional and determines whether to export the column's header or not. Acceptable values are - true and false. By default, the exporter exports the columns header. The fourth parameter is optional and determines the array of rows to be exported. By default all rows are exported. Set null, if you want all rows to be exported. The fifth parameter is optional and determines whether to export hidden columns. Acceptable values are - true and false. By default, the exporter does not export the hidden columns. The sixth parameter is optional and determines the url of the export server. By default, the exporter is hosted on a jQWidgets server. The last parameter is optional and determines the char set. Code example

Invoke the exportdata method.

 $("#jqxGrid").jqxGrid('exportdata', 'json', 'jqxGrid');

Code example with custom URL parameter

$("#jqxGrid").jqxGrid('exportdata', 'json', 'jqxGrid', true, null, true, http://www.myserver.com/save-file.php);

Export to Excel works with the ExcelML format. ExcelML is XML-based file format. It complies to the Microsoft XMLSS specification and is supported in Microsoft Office 2003 and later. * When you open export to Excel, you may receive the following message: "The file you are trying to open, 'file_name.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening this file. Do you want to open the file now?" The reason of this warning message is explained in details in the following post: excel-2007-extension-warning.aspx

Upvotes: 1

Related Questions