How to enable jQgrid to Export data into PDF/Excel
Asked Answered
D

4

11

I am new in jQuery/jQgrid coding. I am using jQgrid version is 4.4.4 & jQuery 1.8.3. I want to enable export to PDF/EXCEL functionality in my jQgrid. For that I referred following links - Click Here and Click Here. On the basis of this links, I developed few lines of code in jquery which is as follows:

   .jqGrid('navGrid', topPagerSelector, { edit: false, add: false, del: false, search: false, pdf: true}, {}, {}, {}, {}
   }).jqGrid('navButtonAdd',topPagerSelector,{
    id:'ExportToPDF',
    caption:'',
    title:'Export To Pdf',
    onClickButton : function(e)
    {
        try {
            $("#tbPOIL").jqGrid('excelExport', { tag: 'pdf', url: sRelativePath + '/rpt/poil.aspx' });
        } catch (e) {
            window.location = sRelativePath + '/rpt/poil.aspx&oper=pdf';
        }
    },
    buttonicon: 'ui-icon-print'
});

But this code is not working properly. I searched on internet google a lot but I am not getting useful & relevant info to achieve my task. Is anyone know how to do this???

UPDATE: I a am not using paid version of jqgrid.

Defile answered 1/2, 2014 at 6:7 Comment(7)
What you have tried in your excelExport function?Acridine
Actually according to that links, If you refer Source code of that links page, I thought by setting pdf:true and giving excelExport function it will export to PDF format. But It won't.Defile
I search on net, in some links people told that we can't export data to PDF instead you paid version of jQgrid or We will need to look for server side (PHP) solution. But unfortunately I don't know PHP.Defile
No, You need to write excelExport function for export your grid content into server. There you can print it in PDF.Acridine
You need not to use paid version to export into PDF.Acridine
@ Vinoth Krishnan: Please sir can you tell me how to do that... I really don't know. Please suggest me some links or code snippet so that on the basis of that I can developed my code.Defile
let us continue this discussion in chatAcridine
A
5

function to be called inside of your onclick event.

function exportGrid(){
  mya = $("#" + table).getDataIDs(); // Get All IDs
var data = $("#" + table).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 = "<html><head>"
        + "<style script=&quot;css/text&quot;>"
        + "table.tableList_1 th {border:1px solid black; text-align:center; "
        + "vertical-align: middle; padding:5px;}"
        + "table.tableList_1 td {border:1px solid black; text-align: left; vertical-align: top; padding:5px;}"
        + "</style>"
        + "</head>"
        + "<body style=&quot;page:land;&quot;>";


for ( var k = 0; k < colNames.length; k++) {
    html = html + "<th>" + colNames[k] + "</th>";
}
html = html + "</tr>"; // Output header with end of line
for (i = 0; i < mya.length; i++) {
    html = html + "<tr>";
    data = $("#" + table).getRowData(mya[i]); // get each row
    for ( var j = 0; j < colNames.length; j++) {
     html = html + "<td>" + data[colNames[j]] + "</td>"; // output each Row as
                // tab delimited
    }
    html = html + "</tr>"; // output each row with end of line
}
html = html + "</table></body></html>"; // end of line at the end
alert(html);
html = html.replace(/'/g, '&apos;');
//  var form = "<form name='pdfexportform' action='generategrid' method='post'>";
//  form = form + "<input type='hidden' name='pdfBuffer' value='" + html + "'>";
//  form = form + "</form><script>document.pdfexportform.submit();</sc"
//      + "ript>";
//  OpenWindow = window.open('', '');
//  OpenWindow.document.write(form);
//  OpenWindow.document.close();
}
Acridine answered 1/2, 2014 at 10:1 Comment(6)
Here table is your ID of jQgrid.Acridine
Ok sir, But you have not comment + "'>"; and + "ript>"; this line. Should I comment it or it is necessary for code??Defile
You will find your html content in your alert(html). That is end of javascript side. You need to uncomment (all commented line at last) after your content verified in alert message.Acridine
let us continue this discussion in chatAcridine
I used something similar to this and end up with a xls file...but since this basically builds a HTML table I get a warning when opening it, and then if I try to save it wants to save it as a Web Page. Does the same thing happens to others? And is there a solution to that?Gilleod
Yes it builds a HTML table since it's javascript. But we did send this html data to server side and change the content type into excel. Hope you haven't tried that.Acridine
D
9

Here is a clever solution to save the jqGrid data as excel sheet: (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.

Disbelieve answered 16/11, 2015 at 10:44 Comment(1)
Thank you for share your code, yes it works. But could we use this code with the Russian language? I mean now it show like "Реестр_тест_1708"Britney
A
5

function to be called inside of your onclick event.

function exportGrid(){
  mya = $("#" + table).getDataIDs(); // Get All IDs
var data = $("#" + table).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 = "<html><head>"
        + "<style script=&quot;css/text&quot;>"
        + "table.tableList_1 th {border:1px solid black; text-align:center; "
        + "vertical-align: middle; padding:5px;}"
        + "table.tableList_1 td {border:1px solid black; text-align: left; vertical-align: top; padding:5px;}"
        + "</style>"
        + "</head>"
        + "<body style=&quot;page:land;&quot;>";


for ( var k = 0; k < colNames.length; k++) {
    html = html + "<th>" + colNames[k] + "</th>";
}
html = html + "</tr>"; // Output header with end of line
for (i = 0; i < mya.length; i++) {
    html = html + "<tr>";
    data = $("#" + table).getRowData(mya[i]); // get each row
    for ( var j = 0; j < colNames.length; j++) {
     html = html + "<td>" + data[colNames[j]] + "</td>"; // output each Row as
                // tab delimited
    }
    html = html + "</tr>"; // output each row with end of line
}
html = html + "</table></body></html>"; // end of line at the end
alert(html);
html = html.replace(/'/g, '&apos;');
//  var form = "<form name='pdfexportform' action='generategrid' method='post'>";
//  form = form + "<input type='hidden' name='pdfBuffer' value='" + html + "'>";
//  form = form + "</form><script>document.pdfexportform.submit();</sc"
//      + "ript>";
//  OpenWindow = window.open('', '');
//  OpenWindow.document.write(form);
//  OpenWindow.document.close();
}
Acridine answered 1/2, 2014 at 10:1 Comment(6)
Here table is your ID of jQgrid.Acridine
Ok sir, But you have not comment + "'>"; and + "ript>"; this line. Should I comment it or it is necessary for code??Defile
You will find your html content in your alert(html). That is end of javascript side. You need to uncomment (all commented line at last) after your content verified in alert message.Acridine
let us continue this discussion in chatAcridine
I used something similar to this and end up with a xls file...but since this basically builds a HTML table I get a warning when opening it, and then if I try to save it wants to save it as a Web Page. Does the same thing happens to others? And is there a solution to that?Gilleod
Yes it builds a HTML table since it's javascript. But we did send this html data to server side and change the content type into excel. Hope you haven't tried that.Acridine
S
5

If you are on PHP, try phpGrid. Then you just need to call

$dg->enable_export('PDF'); // for excel: $dg->enable_export('EXCEL'); 

check out http://phpgrid.com/example/export-datagrid-to-excel-or-html. It generates jqGrid javascript required for rendering grid.

Symploce answered 15/4, 2015 at 10:37 Comment(0)
C
-2
    if (exportexcel.Equals(excel) )
   {
        GridView view = new GridView();
        string conn = @"Server=localhost;port=3306;Database=jtext;Uid=root;Password=techsoft";
        IFormatProvider culture = new System.Globalization.CultureInfo("fr-Fr", true);
        MySqlConnection con = new MySqlConnection(conn);
        con.Open();
        MySqlCommand cmd = new MySqlCommand(query, con);
        MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        view.DataSource = ds;
        view.DataBind();
        con.Close();
        HttpContext Context = HttpContext.Current;
        context.Response.Write(Environment.NewLine);
        context.Response.Write(Environment.NewLine);
        context.Response.Write(Environment.NewLine);
        DateTime ss = DateTime.Now;
        string custom = ss.ToString("dd-MM-yyyy");
        string sss = DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
        string aaa = "Generated Date and Time : " + custom + "  " + sss;
        context.Response.Write(aaa);
        context.Response.Write(Environment.NewLine);
        foreach (DataColumn column in ds.Tables[0].Columns)
        {
            context.Response.Write(column.ColumnName + " ,");
        }
        context.Response.Write(Environment.NewLine);
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                context.Response.Write(row[i].ToString().Replace(" ", string.Empty).Replace(",", " ") + " ,");
             }
            context.Response.Write(Environment.NewLine);
        }
        string attachment = "attachment; filename= " + rolefullname + ".xls";
        context.Response.ContentType = "application/csv";
        context.Response.AppendHeader("Content-Disposition", attachment);
         }
       }

strong text

Consumerism answered 27/11, 2015 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.