php + jqgrid + export to excel - php

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

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){
}

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 ~

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

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

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.

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.

Related

Cannot properly view special letters ( such as the french accents ) after converting a HTML table to CSV [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Special characters not being displayed correctly when being written to a csv file in excel
(2 answers)
Closed 8 months ago.
so to better describe my problem :
1- i aquire data from Mysql database
2- I organise it into my Html Table with an id of : id="#Elements"
while ($row = $result->fetch_assoc()) {
echo('<tr>');
echo '<td>'.$row["Rang"].'</td>';
echo '<td>'.$row["Pays"].'</td>';
echo '<td>'.$row["Region"].'</td>';
echo '<td>'.$row["Documents"].'</td>';
echo '<td>'.$row["Documents_citables"].'</td>';
echo '<td>'.$row["Citations"].'</td>';
echo '<td>'.$row["Autocitations"].'</td>';
echo'<td>'.$row["Citations_par_document"].'</td>';
echo '<td>'.$row["Indiceh"].'</td>';
echo '<td>'.$row["Discipline"].'</td>';
echo '<td>'.$row["Sous_discipline"].'</td>';
echo '<td>'.$row["Annee"].'</td>';
echo( '</tr>');
}
3- In my js file , i tried to convert this table to Csv using these two functions :
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++){
row.push(cols[j].innerText);
console.log(cols[j].innerText);
}
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
For the button that calls the function :
<button id="download-csv" class="downloadcsv" onclick="exportTableToCSV('data.csv');">Télécharger le tableau</button>
4- i get a CSV file but with unreadable text, for example : Région is shown as Région
My html file is set to Charset UTF-8 and my database is also using default characters in it's settings
Can anyone help me figure out how to fix this issue, or even how to Convert the table to csv in a "cleaner" way. thank you
Note : im only using php and js for this project .

How to find the cell index when rowspans are involved

I am working on a scheduling project and have run into an issue with finding the column index of a selected cell (so that i may then get the appropriate header for the column). The issue comes into play when a previous cell(or cells) have/has a rowspan. In which case the cell index is off by that amount of cells. I have been at this since yesterday. My current attempt involves using a solution I found in previous posts, and this is this:
parentTr.find('>td, >th').each(function(i,o) {
if ( this == reference )
{
cellNum = i;
var counter = columnNum;
while ( counter-- )
{
$(this).closest('tr').next().find('>td,>th').each(function(i,o)
{
if ( cellNum == i )
{
$(this).addClass('rowspan-affected');
$(this).attr('colNum', columnNum);
}
});
}
}
});
})
The problem is that this solution counts the number of rowspanned cells on the entire page. I need a count of the rowspanned cells for only the current clicked cell, and then be able to add that count to index so I can get the proper header. What I have been trying looks like this:
var $this = $(this);
//get the row header contents
var row = $this.parent('tr').contents('th:eq(0)').html();
//trying this
var colCount = $(this).prevAll().find('td').parent('tr').attr('rowspan');
alert (colCount);
//used to get the cell index
var rowIndex = $(this).parent().index('.main tbody tr');
var tdIndex = $(this).index('.main tbody tr:eq('+rowIndex+') td');
//alert ("tdindex " + (tdIndex+1));
var headerObj = $(this).parents('.main').find('th').eq(tdIndex+1);
//strip whitespace before passing
var toPass = $.trim(headerObj.text());
//toPass = $.trim(toPass)
//alert (toPass);
This information is gathered and then passed to a new form with the selected information used to populate the form.
If anyone can help me with this, I would be greatly appreciative!!!

How to print rows with JavaScript

I am currently using
rows.length
in JS and it's giving me the number of rows as output.
The actual code is like this
oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
The output is Number of Rows = 1
But I want to see the values of the rows not the number of rows.
The whole function looks like below after editing:
this.get_resources = function(rows)
{ var oResources = $('#resources-'+ options.plugin_uuid);
//oResources.html("<h3>Number of Rows = "+ rows.length+"</h3>");
//oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data
//console.log(rows.length);
};
Now it's printing out [object] [object]
My question is:
The output is supposed to be an email id instead of [object] [object]. How to solve this?
Something like that?
oResources.html("<h3>Content of Rows = "+ rows.join(' :: ')+"</h3>");
EDIT: As your data format seems to have another level of depth, I've made a fiddle to give some insight on what you could do. http://jsfiddle.net/TyeQE/
try this:
var data = ""; // Temporary `data` variable
for(var key in rows) { // Loop through the rows
if(rows.hasOwnProperty(key)){
data += rows[key] + "<br />\n"; // Add the current row to the data
}
}
oResources.html(data); // Display the data
Yes, 'rows' looks like an array. You need a for loop to go over the array and print it out.
var str = ""
for(var i = 0; i < rows.length; i++) {
str = rows[i] + "<br>";
}
oResources.html($str);
Try console.log(rows). Open console (usualy F12) in the browser to see the result.

Populate Select list Menu though Ajax Jquery

Before anybody says this is a duplicate of this and that question, let me assure you I have tried the solutions there and I have failed. I am using a solution offered in this website to come up with my solution and I believe I am 90% done except for one error. I want to display a list of all codes that have a certain common ID associated with them.
Here is my PHP code that I am using to get a list of codes
<?php
$budgetcode=$_POST['budgetcode'];
//$budgetcode=2102;
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$T1=($row['T1']);
$T2=($row['T2']);
$T3=($row['T3']);
$T4=($row['T4']);
$optionValue = $T1."-".$T2."-".$T3."-".$T4;
echo json_encode("<option>$optionValue</option");
// echo json_encode('1');
}
}
?>
Here is the ajax call i am using to fetch the codes
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(data!='0')
{
$("#budgetcode").html(data).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
//alert(budgetid);
})
The problem here is that jquery does not understand the data it is receiving if it is not numeric. E.g if I comment out the json_encode('1') and put random html code instead of data in my success part, I get results displayed in my browser. Can anybody tell me why jquery is only recognizing numeric values that are being echoed from PHP and not varchar values. Using jquery 1.4.2. Any help appreciated.
EDIT
I have managed upto some point and now i am stuck. I have used John's Answer and here is my jquery code. i just need to split the array and append each element to a variable one at a time like here
here is the code. Somebody please tell how I split (data). i can alert it but it is comma seperated. Just need to get the individual items append them to variable html and then display it.
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
// alert(split (data))
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option>' +data+ '</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
I would skip JSON altogether:
PHP
echo "<option>$optionValue</option>";
Everything else should work.
Finally figured it out. Here is the php code
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$data[] = $row;
}
echo json_encode($data);
}
?>
Here is the jquery code
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
var html = '';
var joiner='';
var len = data.length;
for (var i = 0; i< len; i++) {
joiner=([data[i].T1,data[i].T2,data[i].T3, data[i].T4].join('-'));
//alert(joiner);
html += '<option>'+joiner+'</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
Had to use join to join the multiple codes using a dash. Hope this helps. The PHP part and part of the jquery was inspired by this question
FWIW, for populating select lists I usually use the following jQuery code:
// populates select list from array of items given as objects: {
name: 'text', value: 'value' }
function populateSelectList(parent, items) {
parent.options.length = 0;
if (parent.options.length === 0) {
parent.options[0] = new Option("Please select something...", "");
}
$.each(items, function (i) {
if (typeof (this) == 'undefined') { return; }
parent.options[el.options.length] = new Option(this.name, this.value);
});
}
and to call the above function i pass the results of an ajax call using the map method where #select is the selector for the parent select element. I am setting the Text property to the name and Value to the value but that should change according to the objects returned by the ajax call (e.g. assuming the returned objects have a Value and Text properties).
populateSelectList($('#select').get(0), $.map(results, function
(result) { return { name: result.Text, value: result.Value} }));

Access javascript DOM objects in PHP

I have a javascript code helping me to dynamically create row after row in a table and to delete a row from that table.
each row has four cells. cell 1 for instance contains a text zone.
to differentiate cell1 from row 1 with cell1 from row 2, I rename my cell 1 like that cell1.name= cell1.name + '_' + row.rowIndex.
I create a submit button so that I could read data entered by a user in the rows of the table and I try to print $_GET. but there is nothing inside. How could I access to my DOM objects in PHP?
I am grateful for your help.
my HTML + PHP code
<body >
<?php
if (isset($_GET['Enter'])){
print_r($_GET);
}
?>
<h1> Create an Item </h1>
<form method="GET" action="func.html">
<table align="center" border = "2" cellspacing ="0" cellpadding="3" id="table">
<tr><td><b>Functionality Name:</b></td> <td><b>Description:</b></td> <td><b>Status:</b></td> <td><input type="button" Name= "Ajouter" Value="Ajouter" onclick="go()"></td></tr>
</table>
<input type="submit" name="submit" value="Enter">
</form>
</body>
and my Javascript code:
<script>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox and others
xhr = new XMLHttpRequest();
else if(window.ActiveXObject){ // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest not supported by your browser
alert(" Your browser does not support XMLHTTPRequest objects...");
xhr = false;
}
return xhr
}
/**
* method called when the user clicks on the button
*/
function go(){
var xhr = getXhr()
// We defined what we gonna do with the response
xhr.onreadystatechange = function(){
// We do somthing once the server's response is OK
if(xhr.readyState == 4 && xhr.status == 200){
var body = document.getElementsByTagName("body")[0];
// Retrieve <table> ID and create a <tbody> element
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell_1 = document.createElement("td");
var cell_2 = document.createElement("td");
var cell_3 = document.createElement("td");
var cell_4 = document.createElement("td");
// Create the first cell which is a text zone
var cell1=document.createElement("input");
cell1.type="text";
cell1.name="fname";
cell1.size="20";
cell1.maxlength="50";
cell_1.appendChild(cell1);
// Create the second cell which is a text area
var cell2=document.createElement("textarea");
cell2.name="fdescription";
cell2.rows="2";
cell2.cols="30";
cell_2.appendChild(cell2);
// Create the second cell which is a combo box
var cell3 = document.createElement("div");
cell3.id="rs";
cell3.innerHTML=xhr.responseText;
cell_3.appendChild(cell3);
// Create the fourth cell which is a button
var cell4=document.createElement("input");
cell4.type="button";
cell4.value="Delete"
cell4.onclick=delRow;
cell_4.appendChild(cell4);
// add cells to the row
row.appendChild(cell_1);
row.appendChild(cell_2);
row.appendChild(cell_3);
row.appendChild(cell_4);
// add the row to the end of the table body
tblBody.appendChild(row);
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// Rename cells with the row index
var ind=row.rowIndex;
var liste_fname = row.getElementsByTagName("input");
for(i=0; i < liste_fname.length; i++)
{
if(liste_fname[i].name == "fname")
{
liste_fname[i].name = liste_fname[i].name + "_" + ind; //give fname_1, fname_2, fname_3, ...
}
}
var fd = row.getElementsByTagName("textarea");
fd[0].name = fd[0].name + "_" + ind;
var cd = row.getElementsByTagName("div");
cd[0].id = cd[0].id + "_" + ind;
var selectname = row.getElementsByTagName("select");
selectname[0].name = selectname[0].name + "_" + ind;
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 1;
tbl.setAttribute("border", "1");
}
}
xhr.open("GET","fstatus.php",true);
xhr.send(null);
}
function delRow(){
var i= this.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(i);
}
</script>
Best regards,
Billy
Because PHP is server side and Javascript is Client side you can't directly access elements on the page.
In order to access elements you need to post back to the server via a FORM or some AJAX.
You might look into jQuery to help you do this since it makes it easier to call your PHP programs and manipulate the DOM.
I'm going to second the use of jQuery. It'll be tidier and keep you neatly in a single paradigm during this particular task.
One way to do this with PHP would be to dump your DOM object into JSON and then use PHP's JSON support. Depending on your purposes, you can roll your own class to process the JSON data or just grab it from the array you get from json_decode(). Another way would be to dump the object into its representative HTML and pass that to your PHP script rather than the DOM object. You can then reparse it using The Simple HTML DOM Parser, an easy-to-use, freely available DOM parser for PHP.
Of course, you should note that you're adding two processing steps here. If you can do the processing you need to do without switching languages, you're saving time and a bit of sanity.
Well... for starters you want to see if $_GET['submit'] is set not $_GET['Enter'] because $_GET['submit'] should have the value of 'Enter'.
Also, each of your textarea's need to have a different name from the rest, so they don't overwrite each other ( Or they need to have a name that ends in [] (square brackets) and then php will turn them into an array).
And once the html is submitted... the DOM doesn't exist anymore so PHP can't really access it except through ajaxy kinf of stuff.
your cell name should not named like that ... it should be like this
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
.....
<input type='submit' name='submit' value='submit'/>
so you can access from php as array of username
$_GET[username][0] for example will display the first username etc ...
btw, try to use prototype or jquery (javascript framwork) it will simplify your life a lot.
to post data using jquery using ajax:
var url = 'your.server.com/post/fstatus.php';
var data = $('#myform_id').serialize();
$.post(url, data , function(result){
//... if the data was alright or submited ...
alert(result);
},"json");
isn't it easier ? :)
to append a simply type:
var newfield="<div id='rs'><textarea name='mytextarea'></div>"; $('#your_target_id').append(newfield);
in your php type
<?php print_r($_GET); ?>
and you will see what i mean :)
I cannot stress enough - use jQuery. Your life will be an order of magnitude simpler.

Categories