Jqgrid export to excel

Somebody knows a way to export the data from a jqgrid to excel?

I want to do a report using this jqgrid that i think is awsome. But i need to save or print this report somehow, because is information to be keeped.
Somebody knows any way??

Justin Ethier's user avatar

Justin Ethier

130k51 gold badges227 silver badges284 bronze badges

asked Feb 3, 2010 at 0:11

Paulo's user avatar

This is my approach, just add this code to your js/html file

$("#list").jqGrid('navGrid', '#pager',{view:true, del:false, add:false, edit:false, excel:true})
                .navButtonAdd('#pager',{
                                caption:"Export to Excel", 
                                buttonicon:"ui-icon-save", 
                                onClickButton: function(){ 
                                  exportExcel();
                                }, 
                                position:"last"
                            });

        function exportExcel()
        {
            var mya=new Array();
            mya=$("#list").getDataIDs();  // Get All IDs
            var data=$("#list").getRowData(mya[0]);     // Get First row to get the labels
            var colNames=new Array(); 
            var ii=0;
            for (var i in data){colNames[ii++]=i;}    // capture col names
            var html="";
            for(i=0;i<mya.length;i++)
                {
                data=$("#list").getRowData(mya[i]); // get each row
                for(j=0;j<colNames.length;j++)
                    {
                    html=html+data[colNames[j]]+"t"; // output each column as tab delimited
                    }
                html=html+"n";  // output each row with end of line

                }
            html=html+"n";  // end of line at the end
            document.forms[0].csvBuffer.value=html;
            document.forms[0].method='POST';
            document.forms[0].action='csvExport.php';  // send it to server which will open this contents in excel file
            document.forms[0].target='_blank';
            document.forms[0].submit();
        }

PHP script

header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=file.xls");
header("Pragma: no-cache");

$buffer = $_POST['csvBuffer'];

try{
    echo $buffer;
}catch(Exception $e){

}

answered Aug 26, 2010 at 9:33

Felix's user avatar

FelixFelix

3,0506 gold badges42 silver badges53 bronze badges

2

very good question, i was scratching my head off about this as well.
I made it by choosing Felix’s suggestion, let me complete it by adding following lines to your
html body.

<form method="post" action="csvExport.php">
    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
</form>

The only problem i have is the excel file exported doesnt include my column names in jqgrid, also is there a way to exclude a particular or several columns when exporting to excel file?

thank you ~

answered Nov 18, 2010 at 7:57

Patrick's user avatar

PatrickPatrick

731 silver badge6 bronze badges

Great function!
I have made changes.

function exportExcel($id){
  var keys=[], ii=0, rows="";
  var ids=$id.getDataIDs();  // Get All IDs
  var row=$id.getRowData(ids[0]);     // Get First row to get the labels
  for (var k in row) {
    keys[ii++]=k;    // capture col names
    rows=rows+k+"t";     // output each Column as tab delimited
  }
  rows=rows+"n";   // Output header with end of line
  for(i=0;i<ids.length;i++) {
    row=$id.getRowData(ids[i]); // get each row
    for(j=0;j<keys.length;j++) rows=rows+row[keys[j]]+"t"; // output each Row as tab delimited
    rows=rows+"n";  // output each row with end of line
  }
  rows=rows+"n";  // end of line at the end
  var form = "<form name='csvexportform' action='"+php_path+"csvexport.php' method='post'>";
  form = form + "<input type='hidden' name='csvBuffer' value='"+rows+"'>";
  form = form + "</form><script>document.csvexportform.submit();</sc"+"ript>";
  OpenWindow=window.open('', '');
  OpenWindow.document.write(form);
  OpenWindow.document.close();
}

function gridcsvexport(id) {
  $('#'+id).jqGrid('navButtonAdd','#'+id+'_pager',{
    caption:'',
    title:'export',
    buttonicon:'ui-icon-newwin',
    position:'last',
    onClickButton:function (){
      exportExcel($(this));
    }
  });
}

answered Jun 25, 2011 at 16:22

wagner's user avatar

Here is a clever solution to save the jqGrid data as excel sheet without calling the php script: (You just need to call this function with GridID and an optional Filename)

var createExcelFromGrid = function(gridID,filename) {
    var grid = $('#' + gridID);
    var rowIDList = grid.getDataIDs();
    var row = grid.getRowData(rowIDList[0]); 
    var colNames = [];
    var i = 0;
    for(var cName in row) {
        colNames[i++] = cName; // Capture Column Names
    }
    var html = "";
    for(var j=0;j<rowIDList.length;j++) {
        row = grid.getRowData(rowIDList[j]); // Get Each Row
        for(var i = 0 ; i<colNames.length ; i++ ) {
            html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
        }
        html += 'n';
    }
    html += 'n';

    var a         = document.createElement('a');
    a.id = 'ExcelDL';
    a.href        = 'data:application/vnd.ms-excel,' + html;
    a.download    = filename ? filename + ".xls" : 'DataList.xls';
    document.body.appendChild(a);
    a.click(); // Downloads the excel document
    document.getElementById('ExcelDL').remove();
}

We first create a CSV string delimited with ;. Then an anchor tag is created with certain attributes. Finally click is called on a to download the file.

You could have a look at several excel MIME Types : MIME Type List

answered Nov 16, 2015 at 10:46

Suhail Gupta's user avatar

Suhail GuptaSuhail Gupta

22.2k64 gold badges197 silver badges328 bronze badges

I solved your problem .and now iam able to export data excel with column names please refer my code.

function exportExcel()
    {
        var mya=new Array();
        mya=$("#tblnoupdate").getDataIDs();  // Get All IDs
        var data=$("#tblnoupdate").getRowData(mya[0]);     // Get First row to get the labels
        var colNames=new Array(); 
        var ii=0;
        for (var i in data){colNames[ii++]=i;}    // capture col names
        var html="";
            for(k=0;k<colNames.length;k++)
            {
            html=html+colNames[k]+"t";     // output each Column as tab delimited
            }
            html=html+"n";                    // Output header with end of line
        for(i=0;i<mya.length;i++)
            {
            data=$("#tblnoupdate").getRowData(mya[i]); // get each row
            for(j=0;j<colNames.length;j++)
                {
             html=html+data[colNames[j]]+"t"; // output each Row as tab delimited
                }
            html=html+"n";  // output each row with end of line

            }
        html=html+"n";  // end of line at the end
        document.forms[0].csvBuffer.value=html;
        document.forms[0].method='POST';
        document.forms[0].action='<?php echo $baseurl;?>csvexport.php';  // send it to server which will open this contents in excel file
        document.forms[0].target='_blank';
        document.forms[0].submit();
    }

Please let me know if you face any problem.

David Tang's user avatar

David Tang

91.6k30 gold badges166 silver badges149 bronze badges

answered Jan 19, 2011 at 7:39

Vijay's user avatar

VijayVijay

111 bronze badge

0

create a form and a hidden element with the name «csvBuffer». This element gets set by the function.
I had to change the line

html = html+"n"

to

html = html+"\n"

in order to escape it properly.

answered Nov 3, 2010 at 21:18

Antonia's user avatar

AntoniaAntonia

311 silver badge2 bronze badges

Download source — 1.8Mb

Introduction

This walkthrough takes the C# code which I documented in my CodeProject «Free Export to Excel C# class» article, and extends it to allow you to export your data directly from a jqGrid control, into a real Excel .xlsx file.

Last year, I wrote the «Export to Excel» C# class as I couldn’t find any articles on the internet showing how to easily create a real Excel file in C#. Using that class, you can export any DataSet, DataTable or List<> into a real Excel file using the OpenXML libraries simply by calling one CreateExcelDocument function:

DataSet ds = CreateSampleData();
CreateExcelFile.CreateExcelDocument(ds, "C:\Sample.xlsx");

I’ve been overwhelmed by the feedback (and number of downloads) that this CodeProject article has received.

The same goes for this jqGrid walkthrough. If you Google «jqGrid Export to Excel», you will get numerous hits, but none of them give an easy-to-use (and re-use !) way of doing this, without using third-party software or sending your data to a .php file. You’ll also read lots of developers suggesting that this exporting can’t be done.

Note that this article assumes you are using Visual Studio, as it uses a .ashx handler and the OpenXML libraries.

Our Goal

During this walkthough, we will add an «Export to Excel» button to our jqGrid, and when you click on it, we’ll create a «real» Excel 2007 .xlsx file containing your jqGrid’s data.

Image 1

To keep the code maintainable and easy-to-use, this new button simply needs to call a JavaScript function, passing it the name of your <table> where your jqGrid is stored, and what you would like to call the Excel file:

ExportJQGridDataToExcel("#tblOrders", "CustomerOrders.xlsx");

If you have hidden columns in your jqGrid, these will not get exported to Excel.

The main problem with this scenario is that when the user clicks on the Export button, the data is currently held in a jqGrid on the user’s browser. To use my «Export to Excel» C# class to create the Excel file, we somehow need to transfer a copy of this data back to the server before we can export it.

Big disclaimer: this control assumes that you are using a jqGrid with loadonce set to true.  If this isn’t the case, then my library simply won’t have access to your entire data set, and will just end up exporting the current page of data.

Getting Started

I am assuming that you already have a .NET web application set up, containing a jqGrid control in it.

To add the «Export to Excel» functionality to your app, first, you need to add 5 files to your project. The attached «jqGridExport.zip» file contains the current versions of these files.

  • A copy of my C# «Export to Excel» CreateExcelFile.cs file
  • The two .dlls needed to use Microsoft’s OpenXML libraries (DocumentFormat.OpenXml.dll and WindowsBase.dll)
  • The ExportGridToExcel.ashx handler
  • The jqGridExportToExcel.js JavaScript file

Note that the jqGridExportToExcel.js expects to find the ExportGridToExcel.ashx file in a folder called «Handlers«.  If you decide to save the .ashx file into a different folder, you will need to manually alter the final line in the ExportJQGridDataToExcel function in jqGridExportToExcel.js.

postAndRedirect("/Handlers/ExportGridToExcel.ashx?filename=" + excelFilename, { excelData: excelData });

Next, add References to the two .dll files. Your code should now build without errors.

Image 2

In the following example, I will create a jqGrid control and its paging status bar, using these DOM elements:

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

I want to fill my jqGrid control with Customer Order information from my iNorthwind JSON web service, whose data you can view by clicking on this link:

  • http://www.inorthwind.com/Service1.svc/getOrdersForCustomer/BERGS

Here’s the JavaScript which I have used to create my jqGrid and its pager bar:

function LoadCustomerOrders() {

    
    jQuery.support.cors = true;

    
    $("#tblOrders").jqGrid({
        url: 'http://www.inorthwind.com/Service1.svc/getOrdersForCustomer/BERGS',
        contentType: "application/json",
        datatype: "json",
        data: "{}",
        jsonReader: {
            root: "GetOrdersForCustomerResult",     
            id: "OrderID",                               
            repeatitems: false
        },
        mtype: "GET",
        colNames: ["ID", "Order Date", "Name", 
        "Address", "City", "Postcode", "Shipped Date"],
        colModel: [
            { name: "OrderID", width: 70, align: "center", search: false },
            { name: "OrderDate", search: true, width: 100 },
            { name: "ShipName", search: true, width: 120 },
            { name: "ShipAddress", search: true, hidden: true },
            { name: "ShipCity", search: true, width: 200 },
            { name: "ShipPostcode", search: true, width: 140 },
            { name: "ShippedDate", search: true, width: 80, align: "center" }
        ],
        pager: "#pager",
        width: 'auto',
        height: 'auto',
        rowNum: 10,
        rowList: [],
        loadonce: true,
        sortable: true,
        sortname: "OrderID",
        sortorder: "desc",
        viewrecords: true,
        gridview: true,
        autoencode: true,
        ignoreCase: true,   
        caption: ""
    });

    $('#tblOrders').jqGrid('navGrid', '#pager', {
        search: true,
        searchtext: "Search",  
        edit: false,
        add: false,
        del: false,
        refresh: false
    },
    {}, 
    {}, 
    {}, 
    {
        closeOnEscape: true, closeAfterSearch: true, ignoreCase: true, 
        multipleSearch: false, multipleGroup: false, showQuery: false,
        sopt: ['cn', 'eq', 'ne'],
        defaultSearch: 'cn'
    });
}

There’s really nothing new here.

If you already have a jqGrid control on your webpage, your JavaScript code should look something like that.

To add the new «Export to Excel» button, first, we need to add a navButtonAdd function to our pager:

    $('#tblOrders').jqGrid('navGrid', '#pager', {
        search: true,
        searchtext: "Search",  
        edit: false,
        add: false,
        del: false,
        refresh: false
    },
    {}, 
    {}, 
    {}, 
    {
        closeOnEscape: true, closeAfterSearch: true, ignoreCase: true, multipleSearch: false, multipleGroup: false, showQuery: false,
        sopt: ['cn', 'eq', 'ne'],
        defaultSearch: 'cn'
    }).navButtonAdd('#pager', {
        caption: "Export to Excel",
        buttonicon: "ui-icon-disk",
        onClickButton: function () {
            ExportDataToExcel("#tblOrders");
        },
        position: "last"
    });
}

When the user clicks on this new button, we will call an ExportDataToExcel function, passing it the control where our jqGrid is located.

Here’s what that function looks like:

function ExportDataToExcel(tableCtrl) {
    
    ExportJQGridDataToExcel(tableCtrl, "CustomerOrders.xlsx");
}

This simply function calls the ExportJQGridDataToExcel function in the jqGridExportToExcel.js file, telling it where to find the jqGrid control, and the name of the Excel file we wish to create.

This function has one other nice trick up its sleeve.  

Supposing you had added a formatter to one of the columns in your jqGrid.

Image 3

using code like this:

function formatURL(cellValue, options, rowdata, action) {
    return "<a href='Somepage.aspx?id=" + options.rowId + "' >" + cellValue + " </a>";
}

 $("#tblOrders").jqGrid({
       ...  
       colModel: [
            { name: "OrderID", width: 70, align: "center", search: false },
            { name: "OrderDate", search: true, width: 100 },
            { name: "ShipName", search: true, width: 120, formatter: formatURL },
            { name: "ShipAddress", search: true, hidden: true },
            { name: "ShipCity", search: true, width: 200 },
            { name: "ShipPostcode", search: true, width: 140 },
            { name: "ShippedDate", search: true, width: 80, align: "center" }
        ],

The ExportJQGridDataToExcel function will automatically strip out any <a href> elements and just export the text element. 

And that’s it.

That’s actually all you need to know, to use this class.

How It Works

If you have a look at the ExportJQGridDataToExcel function, you’ll find that it iterates through the rows of data in your jqGrid, and builds one (large ?) tab-separated variable containing all of your jqGrid‘s data, plus a header row.

It then calls the ExportGridToExcel.ashx handler, but as a «POST» call, so it can pass this (potentially large) set of data to the handler.

Once the data arrives at the handler, we’re back on the server-side, and can easily convert this into a DataTable, and call my «Export to Excel» class to create the Excel file.

Release notes

November 2014

Thanks to everyone who’s left comments.  You were right, this library didn’t quite work properly when multiselect was set to true.   My library would attempt to export the first column of data, which actually contained some JavaScript code from jqGrid (to tick/untick the checkbox on that row), and it’d result in a nasty error appearing.

A potentially dangerous Request.Form value was detected from the client (excelData="<input role=").

I have now updated the .js file to avoid this exception.

Final Thoughts

I’ve learned (and had to learn) a lot whilst writing this code.

I’m relatively new to using jqGrid, and I’m sure that there’s a cleaner/safer/more environmentally friendly way of doing this. But, as I said, I couldn’t find any articles offering a .NET-friendly way of exporting from jqGrid to Excel, so I hope this fills a gap.

Please leave some feedback if you find any issues using this library, and don’t forget to leave a rating if you find this code useful.

You can also find some other useful walkthroughs on my blog:

  • http://www.mikesknowledgebase.com

Thanks for reading.

Exporting to Excel is another usefull feature in jqGrid. It is important to note the the generated file in not CSV, but Microsoft Excel XML file. The reason that we do it so, is that in diffrent client machines the variables of type date and datetime and some long numbers are not displayed correct. Using XML file with the appropriate field types, make the file portable to all client machines whitout of loosing the information.

Moreover when a summary rows are used the grid creates a formula and the summary fields are displayed at end of the file.

When this method is used within jqGrid and jqGridEdit classes they should be called separatley in order to perform the export.
When used in jqGridrender class everthing is done automatically when the export to excel is enabled.

Also when used separatley and you want to display diffrent header, width and hide some fields a colmodel array should be configured and passed as parameter to the method. If none is set in this case only column names are used

The array has the following structure and properties

Array( 
    [0]=>Array("label"=>"Some label", "width"=>100, "hidden"=>true, "name"=>"colname"), 
    [1]=>Array(...),
     ...
);

Where

  • label is the header displayed for this field
  • width is the width in pixels
  • hidden (boolean) if set does not export this column
  • name is the name from column model

If set the length of this array should be equal to the number of fields in the SQL command used.

Related Methods

exportToExcel
renderGrid

Related variable(s)

gSQLMaxRows
ExportCommand

Example:
Let suppose that when we export to excel we want to show additionally the ShipAddress and ShipCity and perform a summary on the field Freight. We will use again our example.
For this purpose we will first create a custom button in the navigator and use the build in method for this purpose excelExport. The method is avialble since version 3.6.3 of jqGrid Java Script lib. When used the method passes additinally a variable oper=excel to identify that we want a export to Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP jqGrid Class Example</title> <link rel="stylesheet" type="text/css" media="screen" href="themes/redmond/jquery-ui-1.7.1.custom.css" /> <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" /> <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> <script type="text/javascript"> jQuery(document).ready(function(){ .... // Craeate the grid manually jQuery("#grid").jqGrid({ "colModel":[ {"name":"OrderID","index":"OrderID","label":"ID","width":60, "key":true}, {"name":"OrderDate","index":"OrderDate"}, {"name":"CustomerID","index":"CustomerID"}, {"name":"Freight","index":"Freight"}, {"name":"ShipName","index":"ShipName"} ], "url":"querygrid.php", "datatype":"json", "jsonReader":{repeatitems:false}, "pager":"#pager" }); // Set navigator with search enabled. jQuery("#grid").jqGrid('navGrid','#pager',{add:false,edit:false,del:false}); // add custom button to export the data to excel jQuery("#grid").jqGrid('navButtonAdd','#pager',{ caption:"", onClickButton : function () { jQuery("#grid").excelExport(); } }); ...... }); </script> </head> <body> ...... <table id="grid"></table> <div id="pager"></div> ....... </body> </html>

In PHP code we will use ExportCommand to perform the export.

<?php require_once 'jq-config.php'; require_once "php/jqGrid.php"; require_once "php/jqGridPdo.php"; $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD); $grid = new jqGrid($conn); $grid->SelectCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName FROM orders'; $grid->ExportCommand = 'SELECT OrderID, OrderDate, CustomerID, Freight, ShipName, ShipAddress, ShipCity FROM orders'; $grid->dataType = "json"; $export = $_POST['oper']; if($export == 'excel) // let set summary field $grid->exportToExcel(array('Freight'=>'Freight)); else $grid->queryGrid(); ?>

Содержание

  1. Exporting jqgrid to excel
  2. Exporting jqgrid to excel
  3. Common rules and limitations¶
  4. Export to CSV¶
  5. Export to Excel¶
  6. Custom export to Excel¶
  7. Export to Pdf¶
  8. Export to Html¶

Exporting jqgrid to excel

Moreover when a summary rows are used the grid creates a formula and the summary fields are displayed at end of the file.

When this method is used within jqGrid and jqGridEdit classes they should be called separatley in order to perform the export.
When used in jqGridrender class everthing is done automatically when the export to excel is enabled.

Also when used separatley and you want to display diffrent header, width and hide some fields a colmodel array should be configured and passed as parameter to the method. If none is set in this case only column names are used

The array has the following structure and properties

  • label is the header displayed for this field
  • width is the width in pixels
  • hidden (boolean) if set does not export this column
  • name is the name from column model

If set the length of this array should be equal to the number of fields in the SQL command used.

Example:
Let suppose that when we export to excel we want to show additionally the ShipAddress and ShipCity and perform a summary on the field Freight. We will use again our example.
For this purpose we will first create a custom button in the navigator and use the build in method for this purpose excelExport. The method is avialble since version 3.6.3 of jqGrid Java Script lib. When used the method passes additinally a variable oper=excel to identify that we want a export to Excel.

In PHP code we will use ExportCommand to perform the export.

Last Updated: 12/02/2010 �. | &copy TriRand Ltd., 2010

Источник

Exporting jqgrid to excel

When using Guriddo jqGrid, it is often useful and important to export your data to MS Excel, PDF or CSV file formats in order to make it accessible offline, share it with other users, etc.

The Guriddo jqGrid JS grid provides client Excel, PDF an CSV export functionality (server-agnostic) which can be directly utilized to serve the purpose to share data in the aforementioned ways. To enable it, you can trigger export by invoking the exportToExcel, exportToPdf and exportToCsv methods from the client API of the grid.

Additionally, you have the option to customize the rows/columns and cells of the exported file by intercepting the export event.

Common rules and limitations¶

Below are common rules which are valid for all export methods.

  • The methods export data if datatype parameter is set to local or the loadonce parameter is set to true.
  • The methods does not export data which is requested at server — datatype is json or xml.
  • The methods export the current data set, which means that it exports filtered, sorted and etc data.
  • The hidden columns are not included into the export
  • The columns with property exportcol : false in colModel will be not exported. If set to true the column is exported instead that hidden : true is set
  • When a custom formatter is used, options parameter is extended with a properties: isExported which in this case is set to true and exporttype which can be pdf, csv or excel . This allow custom formatting when export occurred for a different export type.
  • SubGrid(s) (of any kind simple or grid as subgrid) are not exported

Export to CSV¶

A CSV is a comma separated values file/string which allows data to be saved in a table structured format. CSVs look like a garden-variety spreadsheet but with a .csv extension (Traditionally they take the form of a text file containing information separated by commas, hence the name).

CSV files can be used with any spreadsheet program, such as Microsoft Excel, Open Office Calc, or Google Spreadsheets. They differ from other spreadsheet file types in that you can only have a single sheet in a file, they can not save cell, column, or row styling, and can not save formulas

This method does not require additional plugin or external programs. When called the method either propmt to save the exported data to a CSV file or it can return the exported data as CSV string depending on configuration (see below).

To export to CSV file format simple call the method:

Where options is a object with a following default properties:

  • separator — string — defines the separator between the fields
  • separatorReplace — string — string which replaces the separator which can be contained into the field string
  • quote — string — the test which enclosed the field
  • newLine — string — the characters put at end of each row for new line
  • replaceNewLine — string — replace the new line if it is contained into the data field
  • includeCaption — boolean — if false the grid caption will be not exported. Default is true
  • includeLabels — boolean — if false the grid header columns will be not exported. Default is true.
  • includeGroupHeader boolean — if set to false the group header will be not exported if they are activated. Default is true.
  • includeFooter — boolean — if false the footer row will be not included into the export if it is defined. Default is true.
  • includeHeader — boolean — if false the header row will be not included into the export if it is defined. Default is true.
  • fileName — string — the file name to save when data is exported. Default jqGridExport.csv
  • mimetype — string — a way of identifying files on the Internet according to their nature and format in our case CSV type of data. Usually this parameter should not be changed.
  • event — The event raises before building the csv file and is used as custom function to modify the text data before it is exported. Parameter passed to this event is the exported csv string
  • returnAsString — boolean — if set to true the data is returned as CSV string
  • loadIndicator — mixed. If the value is boolean when set to true shows the loading indicator message during the export. If the option is function it is called with parameter ‘show’ when the export begin and with parameter ‘hide’ when the export is ended.
  • treeindent — string — indent the ExpandColumn when treegrid is exporting. Default space

Export to Excel¶

A file with the XLSX file extension is a Microsoft Excel Open XML Format Spreadsheet file. It’s an XML-based spreadsheet file created by Microsoft Excel version 2007 and later.

XLSX files organize data in cells that are stored in worksheets, which are in turn stored in workbooks, which are files that contain multiple worksheets. The cells are positioned by rows and columns and can contain styles, formatting, math functions, and more.

Spreadsheet files made in earlier versions of Excel are saved in the XLS format. Excel files that support macros are XLSM files

jqGrid export the data to Microsoft Excel Open XML Format only.

In order to use the method additional module is needed to be loaded. The name of the module is JSZip. The module is included into the package. More about the installation of this module can be seen here. The JSZip can be loaded via cdnjs.

If the JSZip module is not loaded the export to Excel will fail.

To export to Excel it is needed to load JSZip

and call the method

Where options is a object with the following default properties:

  • includeLabels — boolean — if false the grid header columns will be not exported. Default is true.
  • includeGroupHeader — boolean — if set to false the group header will be not exported if they are activated. Default is true.
  • includeFooter — boolean — if false the footer row will be not included into the export if it is defined. Default is true.
  • includeHeader — boolean — if false the header row will be not included into the export if it is defined. Default is true.
  • fileName — string — the file name to save when data is exported. Default jqGridExport.xlsx
  • mimetype — string — a way of identifying files on the Internet according to their nature and format in our case Excel Open XML type of data. Usually this parameter should not be changed.
  • maxlength — integer — set the max length of the visible string data
  • onBeforeExport (xlsx, rowPos)- event — The event raises before building the zip file and is used as custom function to modify the XML document before it is exported. Parameter passed to this event is the exported XML document and the rowPos (last inserted row index).
  • replaceStr (value) — event — custom event to parse the string data before inserted into the XML document. Parameter passed to this event is a string value. If this function is not defined we use internal parser to replace certain character which are not accepted in the XML document. The build in replace function has the following code:

    customizeData (data) — event — the event raises when the data is prepared for export and before any formatting. The passed parameter is a data ob]ect which contain the following:

    data.body — array containing objects of the rowdata
    data.header — array containing the name property in colModel
    data.footer — array containing footer data if set
    data.labels — array contatining the label values of the header
    data.map — contain the mapping of the header columns (special columns like multibox are ommited in export)
    data.parser — contain the exportoptions of column if it is defined.
    Any value of this object can be manipulated.

    loadIndicator — mixed. If the value is boolean when set to true shows the loading indicator message during the export. If the option is function it is called with parameter ‘show’ when the export begin and with parameter ‘hide’ when the export is ended.

  • treeindent — string — indent the ExpandColumn when treegrid is exporting. Default space
  • visibleTreeNodes — boolean — if set to true only visible tree nodes are exported

When called the method open a save dialog with the exported data. Select Save to save the file or Open to open it with the associated application.

The standard behavior of export to Excel method recognizes data types with help of parser and format it according to defined formats. Currently we recognize the following formats — string, Percent with d.p., Percent, Dollars, Pounds, Euros, Numbers without thousand separators, Numbers 2 d.p. without thousands separators, Negative numbers indicated by brackets, Negative numbers indicated by brackets — 2d.p., Numbers with thousand separators, Numbers with 2 d.p. and thousands separators and dates. The format in Excel is as follow:

If this is not acceptable, then it is possible to disable the parser for certain field. This can be done with the help of the option excel_parser set to false in colModel exportoptions object like this:

In this case we detect numbers not matching leading zeros or a negative and text. If this is not acceptable a custom export formatting can be defined — see above.

By default the string fields are parsed for » » and these are replaced with their HTML equivalent and > with build in replaceStr function. See option replaceStr above.

Custom export to Excel¶

Custom export to excel allow to format the data as defined in exportoptions property in colModel by the developer. The default properties in export options have the following values:

  • excel_parser — this is Boolean property with default value true. In this case the build in parses are used to detect the values and format it according to the formatCode definitions — see above. In case this value is false the build in parsing is disabled and the behavior depend on the next parameter excel_format — see below.
  • excel_format — this is a string value. If the string is empty and the option above excel_parser is false the program detects only numeric and text fields. In case this option is set it try to format the value according to the rules of formatting in excel. With other words this string is a Excel formatting code.
  • replace_format — if defined this function can manipulate the data value and make some replacement on it.
  • excel_header_format — this is a string value. If the string is empty and the option above excel_parser is false the program detects only numeric and text fields. In case this option is set it try to format the header data values according to the rules of formatting in excel. With other words this string is a Excel formatting code.
  • replace_header_format — if defined this function can manipulate the only the header data value and make some replacement on it.

Example: Our standard formatting of dollars places a dollar sign at end of value. In case there is a need to put it at the beginning of the value the following code do this:

Export to Pdf¶

(Portable Document Format)

Portable Document Format (PDF) is a file format used to present and exchange documents reliably, independent of software, hardware, or operating system. Invented by Adobe, PDF is now an open standard maintained by the International Organization for Standardization (ISO). PDFs can contain links and buttons, form fields, audio, video, and business logic.

Today PDF is the most used exchange document format.

jqGrid support export of its data to PDF.

In order to use the method additional module is needed to be loaded. The name of the module is pdfmake. The module is included into the package. More about the installation of this module can be seen here. The pdfmake and vfs_fonts can be loaded via cdn.

Since the pdf creation is a heavy work, please use the method in relative small data set. Using the script on data set with more than 300 rows can cause problems and memory leaks.

To export to PDF it is needed to load the following javascripts

and call the method

where the options is a object with the following properties and default values:

  • title — string — The title of the exported data. Printed only once at top of the first page.
  • orientation — string — defines the orientation of the page. Can be ‘portrait’ or ‘landscape’. Default is ‘portrait’.
  • pageSize — string — defines the size of the page. Default is ‘A4’. For all possible values see here
  • description — string — Free text which is printed after the title at first page. Default null.
  • download — string — defines how to handle the PDF. Available two values — ‘open’ — open the PDF in a new window or ‘download’ — download the PDF with file name set in fileName (see below)
  • includeLabels — boolean — if false the grid header columns will be not exported. Default is true.
  • includeGroupHeader — boolean — if set to false the group header will be not exported if they are activated. Default is true.
  • includeFooter — boolean — if false the footer row will be not included into the export if it is defined. Default is true.
  • includeHeader — boolean — if false the header row will be not included into the export if it is defined. Default is true.
  • fileName — string — the file name to save when data is exported. Default jqGridExport.pdf
  • mimetype — string — a way of identifying files on the Internet according to their nature and format in our case PDF type of data. Usually this parameter should not be changed.
  • onBeforeExport — event — The event raises before building the PDF file and is used as custom function to modify the PDF document definition before it is exported. Parameter passed to this event is the document definition object. For more information refer the pdfmake documentation here. See below the default settings for document definition
  • loadIndicator — mixed. If the value is boolean when set to true shows the loading indicator message during the export. If the option is function it is called with parameter ‘show’ when the export begin and with parameter ‘hide’ when the export is ended.
  • treeindent — string — indent the ExpandColumn when treegrid is exporting. Default «-«
  • visibleTreeNodes — boolean — if set to true only visible tree nodes are exported

The default settings for the document before PDF export are follow:

This definition is passed to the onBeforeExport event and it can be modified for custom purposes.

Below example shows how to make the body font of the table body smaller using the onBeforeExport event.

Export to Html¶

HTML is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS) and JavaScript it forms a triad of cornerstone technologies for the World Wide Web. Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.

This method does not require additional plugin or external programs. When called the method either shows a new html page (with option to print) or it can return the exported data as HTML string depending on configuration (see below).

To export to HTML format simple call the method:

Where options is a object with a following default properties:

  • onBeforeExport — event — The event raises before building the HTML file and is used as custom function to modify the HTML document before it is exported. Parameter passed to this event is the exported html document.
  • includeLabels — boolean — if false the grid header columns will be not exported. Default is true.
  • includeGroupHeader — boolean — if set to false the group header will be not exported if they are activated. Default is true.
  • includeFooter — boolean — if false the footer row will be not included into the export if it is defined. Default is true.
  • includeHeader — boolean — if false the header row will be not included into the export if it is defined. Default is true.
  • tableClass — string — class to be added in the table when exported. Can be added more classes separated with space
  • autoPrint — boolean — if set to true after creating the html document in new browser window a print dialog appear automatically.
  • topText — string — text included at the top of the document
  • bottomText — string — text included at the bottom of the document
  • returnAsString — boolean — if set to true the html document is returned as string
  • treeindent — string — indent the ExpandColumn when treegrid is exporting. Default » «
  • visibleTreeNodes — boolean — if set to true only visible tree nodes are exported

Источник

When searching for a way to do this with jqGrid I see several posts that are quite old, but nothing recent. I am using a php server backend with the data sourced from JSON files. I see the paid version of jqGrid has a php version. Is there a method compatible with the free version of jqGrid that I can use to export a real Excel file (not a csv)?

This is a close solution using another plugin but it has a few issues with jqGrid such as unable to specify filename, no table headers and only current page of data exported.

– MarkT

Dec 9, 2016 at 1:36

Making statements based on opinion; back them up with references or personal experience.

This is our Splunktool team suggestion ✌, we tried and its working fine

$queryexport = ("
      SELECT username, password, fullname FROM ecustomer_users WHERE fk_customer = '".$fk_customer."'
      ");​
      $row = mysql_fetch_assoc($queryexport);​ $result = mysql_query($queryexport); $header = '';​
      for ($i = 0; $i < $count; $i++) {
         $header. = mysql_field_name($result, $i).
         "t";
      }​
      while ($row = mysql_fetch_row($result)) {
         $line = '';
         foreach($row as $value) {
            if (!isset($value) || $value == "") {
               $value = "t";
            } else {
               $value = str_replace('"', '""', $value);
               $value = '"'.$value.
               '"'.
               "t";
            }
            $line. = $value;
         }
         $data. = trim($line).
         "n";
         $data = str_replace("r", "", $data);​
         if ($data == "") {
            $data = "nno matching records foundn";
         }
      }
      header("Content-type: application/vnd.ms-excel; name='excel'"); header("Content-Disposition: attachment; filename=exportfile.xls"); header("Pragma: no-cache"); header("Expires: 0");​
      // output data
      echo $header.
      "n".$data;​ mysql_close($conn);
      `

Button for jqGrid

 $grid.jqGrid("navButtonAdd", {
            caption: "Export<br />To Excel",
            buttonicon: "ui-pg-button-text ui-pg-button-icon-over-text fa-file-excel-o",
            title: "Export to Excel",
            onClickButton: function () {
                exportExcel();
            }
        });

HTML for Form Input

       <form id='_export' method="post" action="jqGrid/export_excel.php">
          <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
       </form>

PHP for Downloading XLS file

$buffer = $_POST['csvBuffer'];


$filename = "baplie_".date('Ymd').
".xls";

header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");

try {
   echo $buffer;
} catch (Exception $e) {

}

I am using DataTables as well for an internal site I created. I use this script to download the table data to a CSV file and it works great. You may have to change a few things so the Id’s and classes match your table, but give this a try.

    
    $('#exportDataTable').click(function() {
       var titles = [];
       var data = [];
       
       $('.dataTable th').each(function() {
          titles.push($(this).text());
       });
       
       $('.dataTable td').each(function() {
          data.push($(this).text());
       });
       
       var CSVString = prepCSVRow(titles, titles.length, '');
       CSVString = prepCSVRow(data, titles.length, CSVString);
       
       var downloadLink = document.createElement("a");
       var blob = new Blob(["ufeff", CSVString]);
       var url = URL.createObjectURL(blob);
       downloadLink.href = url;
       downloadLink.download = "data.csv";
       
       document.body.appendChild(downloadLink);
       downloadLink.click();
       document.body.removeChild(downloadLink);
    });
    
    function prepCSVRow(arr, columnCount, initial) {
       var row = ''; 
       var delimeter = ','; 
       var newLine = 'rn'; 
       
       function splitArray(_arr, _count) {
          var splitted = [];
          var result = [];
          _arr.forEach(function(item, idx) {
             if ((idx + 1) % _count === 0) {
                splitted.push('"' + item + '"');
                result.push(splitted);
                splitted = [];
             } else {
                splitted.push('"' + item + '"');
             }
          });
          return result;
       }
       var plainArr = splitArray(arr, columnCount);
       
       
       
       
       plainArr.forEach(function(arrItem) {
          arrItem.forEach(function(item, idx) {
             row += item + ((idx + 1) === arrItem.length ? '' : delimeter);
          });
          row += newLine;
       });
       return initial + row;
    }
    

Suggestion : 2

If you have hidden columns in your jqGrid, these will not get exported to Excel. When the user clicks on this new button, we will call an ExportDataToExcel function, passing it the control where our jqGrid is located. This walkthrough takes the C# code which I documented in my CodeProject «Free Export to Excel C# class» article, and extends it to allow you to export your data directly from a jqGrid control, into a real Excel .xlsx file. A copy of my C# «Export to Excel» CreateExcelFile.cs file

Last year, I wrote the «Export to Excel» C# class as I couldn’t find any articles on the internet showing how to easily create a real Excel file in C#. Using that class, you can export any DataSet, DataTable or List<> into a real Excel file using the OpenXML libraries simply by calling one CreateExcelDocument function:

DataSet ds = CreateSampleData();
CreateExcelFile.CreateExcelDocument(ds, "C:\Sample.xlsx");

To keep the code maintainable and easy-to-use, this new button simply needs to call a JavaScript function, passing it the name of your <table> where your jqGrid is stored, and what you would like to call the Excel file:

ExportJQGridDataToExcel("#tblOrders", "CustomerOrders.xlsx");

Note that the jqGridExportToExcel.js expects to find the ExportGridToExcel.ashx file in a folder called «Handlers«.  If you decide to save the .ashx file into a different folder, you will need to manually alter the final line in the ExportJQGridDataToExcel function in jqGridExportToExcel.js.

postAndRedirect("/Handlers/ExportGridToExcel.ashx?filename=" + excelFilename, {
   excelData: excelData
});

Here’s the JavaScript which I have used to create my jqGrid and its pager bar:

function LoadCustomerOrders() {

   
   jQuery.support.cors = true;

   
   $("#tblOrders").jqGrid({
      url: 'http://www.inorthwind.com/Service1.svc/getOrdersForCustomer/BERGS',
      contentType: "application/json",
      datatype: "json",
      data: "{}",
      jsonReader: {
         root: "GetOrdersForCustomerResult", 
         id: "OrderID", 
         repeatitems: false
      },
      mtype: "GET",
      colNames: ["ID", "Order Date", "Name",
         "Address", "City", "Postcode", "Shipped Date"
      ],
      colModel: [{
            name: "OrderID",
            width: 70,
            align: "center",
            search: false
         },
         {
            name: "OrderDate",
            search: true,
            width: 100
         },
         {
            name: "ShipName",
            search: true,
            width: 120
         },
         {
            name: "ShipAddress",
            search: true,
            hidden: true
         },
         {
            name: "ShipCity",
            search: true,
            width: 200
         },
         {
            name: "ShipPostcode",
            search: true,
            width: 140
         },
         {
            name: "ShippedDate",
            search: true,
            width: 80,
            align: "center"
         }
      ],
      pager: "#pager",
      width: 'auto',
      height: 'auto',
      rowNum: 10,
      rowList: [],
      loadonce: true,
      sortable: true,
      sortname: "OrderID",
      sortorder: "desc",
      viewrecords: true,
      gridview: true,
      autoencode: true,
      ignoreCase: true, 
      caption: ""
   });

   $('#tblOrders').jqGrid('navGrid', '#pager', {
         search: true,
         searchtext: "Search", 
         edit: false,
         add: false,
         del: false,
         refresh: false
      }, {}, 
      {}, 
      {}, 
      {
         closeOnEscape: true,
         closeAfterSearch: true,
         ignoreCase: true,
         multipleSearch: false,
         multipleGroup: false,
         showQuery: false,
         sopt: ['cn', 'eq', 'ne'],
         defaultSearch: 'cn'
      });
}

To add the new «Export to Excel» button, first, we need to add a navButtonAdd function to our pager:

    $('#tblOrders').jqGrid('navGrid', '#pager', {
          search: true,
          searchtext: "Search", 
          edit: false,
          add: false,
          del: false,
          refresh: false
       }, {}, 
       {}, 
       {}, 
       {
          closeOnEscape: true,
          closeAfterSearch: true,
          ignoreCase: true,
          multipleSearch: false,
          multipleGroup: false,
          showQuery: false,
          sopt: ['cn', 'eq', 'ne'],
          defaultSearch: 'cn'
       }).navButtonAdd('#pager', {
       caption: "Export to Excel",
       buttonicon: "ui-icon-disk",
       onClickButton: function() {
          ExportDataToExcel("#tblOrders");
       },
       position: "last"
    });
    }

Suggestion : 3

By default, the Grid exports the current page of the data with sorting, filtering, grouping, and aggregates applied. To initiate Excel export through code, call the saveAsExcel method. By default, the Grid exports only the current page of data. To export all pages, set the allPages option to true. By default, each Grid exports its content in a separate Excel sheet. For more information, refer to the example on exporting multiple Grids in a single Excel document.

For more information, refer to the online demo on Excel export.

The following example demonstrates how to enable the Excel export functionality of the Grid.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>

    <div id="grid"></div>
    <script>
        $("#grid").kendoGrid({
            toolbar: ["excel"],
            excel: {
                fileName: "Kendo UI Grid Export.xlsx"
            },
            dataSource: {
                type: "odata",
                transport: {
                    read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
                },
                pageSize: 7
            },
            sortable: true,
            pageable: true,
            columns: [
                { width: 300, field: "ProductName", title: "Product Name" },
                { field: "UnitsOnOrder", title: "Units On Order" },
                { field: "UnitsInStock", title: "Units In Stock" }
            ]
        });
    </script>

2._

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>

    <div id="grid"></div>
    <script>
        $("#grid").kendoGrid({
            toolbar: ["excel"],
            excel: {
                allPages: true
            },
            dataSource: {
                type: "odata",
                transport: {
                    read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
                },
                pageSize: 7
            },
            pageable: true,
            columns: [
                { width: 300, field: "ProductName", title: "Product Name" },
                { field: "UnitsOnOrder", title: "Units On Order" },
                { field: "UnitsInStock", title: "Units In Stock" }
            ]
        });
    </script>

Each row has a type field that can be used to distinguish between the various row types in the Grid. The supported values are:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>

    <div class="k-rtl">
      <div id="grid" ></div>
    </div>
    <script>
      $("#grid").kendoGrid({
        toolbar: ["excel"],
        excel: {
          allPages: true
        },
        dataSource: {
          type: "odata",
          transport: {
            read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
          },
          pageSize: 7
        },
        excelExport: function(e) {
          var workbook = e.workbook;
          var sheet = workbook.sheets[0];

          workbook.rtl = true;
          for (var i = 0; i < sheet.rows.length; i++) {
            for (var ci = 0; ci < sheet.rows[i].cells.length; ci++) {
              sheet.rows[i].cells[ci].hAlign = "right";
            }
          }
        },
        pageable: true,
        columns: [
          { width: 300, field: "ProductName", title: "Product Name" },
          { field: "UnitsOnOrder", title: "Units On Order" },
          { field: "UnitsInStock", title: "Units In Stock" }
        ]
      });
    </script>

In some scenarios, you might want to hide given column or multiple columns from being exported. This can be achieved using the Exportable setting.

It can also be set to an Object containing different values for Excel and PDF exporting modes, providing separate options for each:

columns: [{
   field: 'ContactTitle',
   exportable: {
      pdf: true,
      excel: false
   }
}]

Like this post? Please share to your friends:
  • Jpg перевести в word формат онлайн бесплатно
  • Jpg открыть в excel
  • Jpg открывается в word
  • Jpg в word с распознаванием текста конвертер перевести онлайн
  • Jpg в word on line