export to CSV from dynamic table data via PHP - javascript

Let's say I have a dynamic table in php page.... is there a way I can export what I have from the dynamic table to a CSV file (and text file [if possible]) via PHP...
Here I am getting data from table and show it in alert box. But I want to save it in a file. Using php.
Here is my code:
<html>
<head>
<script>
function GetCellValues()
{
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
if (i > 2 )
{
str = str + table.rows[0].cells[3].innerHTML.replace(", ");
}
else
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
if (k > 1)
{
str += inputs[k].value.replace(", ");
}
else
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hiden').value = str;
alert(document.getElementById('hiden').value);
}
</script>
</head>
<body>
<form>
<br>
<h1><u>PROJECT</u> :</h1>
<br>
<input type = "hidden" id = "hiden" name = "hiden" value = "">
<input type = "button" name = "submit" onclick = "GetCellValues()" Value = "SAVE">
<br>
</form>
<?php
$handle = fopen("data.csv", "w");
$hide = $_REQUEST['hide'];
fwrite($handle,$hide);
$file = file('data.csv');
$lines = count($file);
echo'<table id = "project" border = "1" cellpadding="2" cellspacing="0"
style = "width: 60%; margin-left: auto; margin-right: auto; border-color: brown; background-color:silver;">';
echo'<tr cellpadding="100">
<th width="15%">Sl.No.</th>
<th width="15%">Project Name</th>
<th width="15%">ChangeDate</th>
<th width="15%">Changed By</th>
</tr>';
for ($i=1; $i<$lines; $i++)
{
$part = explode(',', $file[$i]);
echo'<tr>
<td align= "center" width="5%">'.$part[0].'</td>
<td align= "center" width="25%"><input type="text" value='.$part[1].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[2].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[3].'></td>
</tr>';
}
echo'</table>';
?>
</body>
</html>

you could use the built in PHP5 function fputcsv
here is a sample code
$result = mysqli_query($con, 'SELECT * FROM table_name');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
It will return a comma separated string for each row written to file.csv:

Related

Transfer Table TD in textbox

This is the way on how I populate data in my table.
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var getval;
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
}
</script>
and this is my table where i put the data based on code above.
<table id = "TableContainer" cellspacing="2" cellpadding="3" width ="100%" align = "center" class="hoverTable">
<tr>
<th bgcolor = "darkgreen"><font color="white">#</font></th>
<th bgcolor = "darkgreen"><font color="white">Area</font></th>
<th bgcolor = "darkgreen" width = "200px"><font color="white">Customer Name</font></th>
<th bgcolor = "darkgreen"><font color="white">Person In Charge</font></th>
<th bgcolor = "darkgreen" width = "250px"><font color="white">Remarks</font></th>
<th bgcolor = "darkgreen"><font color="white">Status</font></th>
<th bgcolor = "darkgreen"><font color="white">Doc. Date</font></th>
<th bgcolor = "darkgreen"></th>
</tr>
<tr>
</tr>
</table>
Please bear with me. this code is perfectly running and im running the code by '<body onLoad = "GenerateTable()"> how ever as what you see on my code there is a code that looks like this.
<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
now it will create an image button for every row in my table and that code has a purpose and that is to transfer the data from td to textbox and other elements and here is my code for that.
<script>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
</script>
this is where the error starts when im clicking the image the row data is not transferring in my textbox whats the error?
Updated Code
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
</script>
TYSM
Could you put your second script $('.click-to-select').click(function(){...}) inside of GenerateTable() and after the for loop? Then check if the click handler is running by putting console.log('The dataid is:' + dataid) in here.
$('.click-to-select').click(function(){...
...
var documentdate = $(this).closest('tr').find('td.docdate').text();
console.log('The dataid is:' + dataid)
$('#dataid').val(dataid)
...
}
I can't tell for sure the order that your code executes because you have two separate script tags here, but it's possible your second script can't bind the click handler because the .click-to-selects haven't been created yet by GenerateTable().
Here is a working fiddle using nth-of-type selectors
First you need to remove the id from td because some of it matches with textbox element.
Then replace it with below line of code and do the same for each column.
var dataid = $(this).parent().siblings('.dataid').text();
I think , This function should be like below
Don't use the php tags because these are javascript variables .
function GenerateTable() {
var data = getData();
var table = document.getElementById("TableContainer");
for (var i = 12; i < data.length; i++) {
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ data[i][0] + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ data[i][1] +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + data[i][2] +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + data[i][3] +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + data[i][4] +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' + data[i][5] +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ data[i][6] +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
}
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
Hopefully , it may help you .

Delete a table row jquery

I have the following script :
<script type="text/javascript">
$(document).ready(function() {
var rowCount = 1;
$(".add_more_rows").click(function() {
rowCount++;
var recRow = '<p id="rowCount' + rowCount + '"><table><tr><td><label>Key Population Type :</label><?php
$query = "SELECT * FROM `kp_types` ORDER BY Name ASC";
if ($result = mysqli_query($link, $query)) { ?> \n\ < select class = "kp_types fieldstyle_with_label"
required = ""
name = "kp_typess[]"
id = "kp_types" > \n\ <? php
while ($idresult = mysqli_fetch_row($result)) {
$kp_type_id = $idresult[0];
$kp_type_name = $idresult[1]; ?> \n\ < option id = "partner_id"
value = "<?php echo $kp_type_id; ?>" > <? php echo $kp_type_name.
' '; ?> < /option>\n\<?php } ?> \n\ < /select>\n\<?php } ?> < /td>\n\ < td > < input name = "kp_targetss[]"
type = "text"
maxlength = "120"
style = "margin: 4px 5px 0 5px;" / > < /td>\n\\
n\
< td > < span id = "remove_row' + rowCount + '"
onClick = "javascript:fnRemove(this);"
class = "remove_row' + rowCount + '"
style = "font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" > Delete Entry < /span> </td > < /tr> </table > < /p>';
$('.remove_row' + rowCount + '').click(function() {
alert('.remove_row' + rowCount + '');
$('#rowCount' + rowCount).remove();
alert('#rowCount' + rowCount);
});
$('#addedRows').append(recRow);
});
});
function fnRemove(t) {
$(t).parent('p').remove();
}
</script>
I have tried deleting the entry using the function fnRemove(t) which is a table data in the table but it fails but when I do it while I remove the table elements and remain only with the tr and td , it deletes an entry well. How can I solve this error inside the table element ?
in function fnRemove your parent('p') is mistake
and correct is parents('p')
try this,it worked for me
function fnRemove(t) {
$(t).parents('p').remove();
}

insert dropdown field from mysql using jquery

hi i have a page of invoice where i can add rows using jquery. i am able to add plain text box from .js file but i want to add a drop down menu insted of textbox. justlike default row in php page.
my page code is
<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("inventory_erp",$con);
$getitem=mysql_query("SELECT * FROM 0_stock_master ORDER BY stock_id ASC");
$item = '';
while($row = mysql_fetch_assoc($getitem))
{
$item .= '<option value = "'.$row['id'].'">'.$row['stock_id'].'</option>';
}
$getdescription=mysql_query("SELECT * FROM 0_stock_master ");
$description = '';
while($row2 = mysql_fetch_assoc($getdescription))
{
$description .= '<option value = "'.$row2['description'].'">'.$row2['description'].'</option>';
}
?>
<!DOCTYPE html>
<!-- saved from url=(0047)http://css-tricks.com/examples/EditableInvoice/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Editable Invoice</title>
<script src="./Editable Invoice_files/jquery-1.3.2.min.js"></script>
<script src="./Editable Invoice_files/example.js"></script>
</head>
</html>
<table id="items">
<tbody><tr>
<th>Item</th>
<th>Description</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $item; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><select name="age"> <?php echo $description; ?> </select></td>
<td><textarea class="cost">$0.00</textarea></td>
<td><textarea class="qty">1</textarea></td>
<td><span class="price">$0.00</span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value"><div id="total">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid">$0.00</textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due">$0.00</div></td>
</tr>
</tbody></table>
i am using a example.js file to add rows dynamically.
example.js
function print_today() {
// ***********************************************
// AUTHOR: WWW.CGISCRIPT.NET, LLC
// URL: http://www.cgiscript.net
// Use the script, just leave this message intact.
// Download your FREE CGI/Perl Scripts today!
// ( http://www.cgiscript.net/scripts.htm )
// ***********************************************
var now = new Date();
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
var today = months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
return today;
}
// from http://www.mediacollege.com/internet/javascript/number/round.html
function roundNumber(number,decimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
numString += ".";// give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff,cutoff+1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0,cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
for(var i=0;i<decimals-decs;i++) newString += "0";
//var newNumber = Number(newString);// make it a number if you like
return newString; // Output the result to the form field (change for your purposes)
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("$"+total);
$('#total').html("$"+total);
update_balance();
}
function update_balance() {
var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
due = roundNumber(due,2);
$('.due').html("$"+due);
}
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
update_total();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
$(document).ready(function() {
$('input').click(function(){
$(this).select();
});
$("#paid").blur(update_balance);
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $option; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea>Description</textarea></td><td><textarea class="cost">$0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
update_total();
if ($(".delete").length < 2) $(".delete").hide();
});
$("#cancel-logo").click(function(){
$("#logo").removeClass('edit');
});
$("#delete-logo").click(function(){
$("#logo").remove();
});
$("#change-logo").click(function(){
$("#logo").addClass('edit');
$("#imageloc").val($("#image").attr('src'));
$("#image").select();
});
$("#save-logo").click(function(){
$("#image").attr('src',$("#imageloc").val());
$("#logo").removeClass('edit');
});
$("#date").val(print_today());
});
i am using this code in exampe.js file to add text box (Description) in new row. but i want a drop down menu from mysql database.

how to write javascript code within php

I have got a form, on clicking the submit button:
<form>
<h2 style="text-align: center">* * * PROJECTS * * *</h2>
<br>
<input type="button" name="submit" onclick="document.write('<?php GetCellValues() ?>');" Value="SAVE">
<br>
</form>
<?php
function GetCellValues()
{
echo("Save");
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
}
?>
<?php
$handle = fopen("data.csv", "w");
$hide = $_REQUEST['hide'];
fwrite($handle,$hide);
$file = file('data.csv');
$lines = count($file);
echo'<table id = "projest" border = "1" cellpadding="2" cellspacing="0" style = "width: 60%; margin-left: auto; margin-right: auto; border-color: brown; background-color:gray;">';
echo'<tr cellpadding="100">
<th width="15%"><h3>Sl.No.</h3></th>
<th width="15%"><h3>Project Name</h3></th>
<th width="15%"><h3>ChangeDate</h3></th>
<th width="15%"><h3>Changed By</h3></th>
</tr>';
for ($i=1; $i<$lines; $i++)
{
$part = explode(',', $file[$i]);
echo'<tr>
<td align= "center" width="5%">'.$part[0].'</td>
<td align= "center" width="25%"><input type="text" value='.$part[1].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[2].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[3].'></td>
</tr>';
}
echo'</table>';
?>
But not able to submit the form, if I call the javascript code on onClick, it works.what is the problem in this code, Is there any work around for this?
You have to echo the whole JScript function because PHP doesn't know what you're doing:
echo "<script type = 'text/javascript'>function GetCellValues()
{
//echo('Save'); use document.write()?
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
}</script>";
<?php
echo "<script> your javascript code </script>";
?>
php will work from server javascript will work from client side
You cannot mix javascript code (which is executed on client side) and php (which is server oriented).
First, your function GetCellValues is javascript, not php, so replace your firsts <?php and ?> by <script> and </script>.
Then, you need a form and a button type=submit, or an ajax call.

Export HTML visible table column content to client side, 2010 Excel page

With F12 debug, the JQuery codes is able to skip hidden column cell, only exort cells not hidden, but the >last statement, window.open NOT able to bring it up on the 2010 EXCEL page.
The following code has been simplied to focus the problem, not able to export HTML table to 2010 Execel
<body>
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td style="display: none"> sechs</td></tr>
</table>
<br />
Test: <input id="ExportExcel" type='submit' value='Export Excel'>
<script type="text/javascript">
$(document).ready(function () {
$('#ExportExcel').click(function () {
var html;
var numofRows;
var gTable = document.getElementById('myGrid');
numofRows = gTable.rows.length - 1;
var numofCells;
var trhtml = "";
numofCells = gTable.rows[0].cells.length - 1;
for (r = 0; r <= numofRows; r++) {
var c = 0;
var tdhtml = "";
for (c = 0; c <= numofCells; c++) {
if (!(gTable.rows[r].cells[c].currentStyle.display == "none")) {
var tempstr = gTable.rows[r].cells[c].innerText;
tdhtml = tdhtml + "<td>" + gTable.rows[r].cells[c].innerText + "</td>";
}
}
trhtml = trhtml + "<tr>" + tdhtml + "</tr>";
}
html = "<table border='1'>" + trhtml + "</table>";
// MS OFFICE 2003 : data:application/vnd.ms-excel
// MS OFFICE 2007 : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
window.open('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + encodeURIComponent(html));
});
});
</script>
</body>
Ans For the above question:
Here i added class to hidden td
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td class="xyz" style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td class="xyz" style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td class="xyz" style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td class="xyz" style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td class="xyz" style="display: none"> sechs</td></tr>
</table>
when click on export add this statement -> $('.xyz').remove();
like this
$('#ExportExcel').click(function () {
$('.xyz').remove();
// add export statements here
});
it will work
After export, the class xyz related td's are not displaying in your excel.
The attached JQuery codes will export visible column header, and row cell content to client side Excel ; just copy and paste the following codes to become part of Javascript codes (insert into question codes), and change button id to ExportExcel2. NOTE: assumption: client has Excel installed.
$('#ExportExcel2').click(function () {
str = "";
var myTable = document.getElementById('myGrid');
var rows = myTable.getElementsByTagName('tr');
var rowCount = myTable.rows.length;
var colCount = myTable.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelWorkbook = ExcelApp.Workbooks.Add();
var ExcelSheet = ExcelWorkbook.ActiveSheet; //new ActiveXObject("Excel.Sheet");
//ExcelSheet.Application.Visible = true;
ExcelApp.Visible = true;
ExcelSheet.Range("A1", "Z1").Font.Bold = true;
ExcelSheet.Range("A1", "Z1").Font.ColorIndex = 23;
//Format table headers
var tarcol = 0;
for (var i = 0; i < 1; i++) {
targetCol = 1;
for (var j = 0; j < colCount; j++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].currentStyle.display == "none")) {
str = myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
//ExcelSheet.Cells(i + 1, j + 1).Value = str;
ExcelSheet.Cells(i + 1, targetCol).Value = str;
targetCol += 1;
}
}
ExcelSheet.Range("A1", "BD1").EntireColumn.AutoFit();
}
for (var i = 1; i < rowCount; i++) {
targetCol = 1;
for (var k = 0; k < colCount; k++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("td")[k].currentStyle.display == "none")) {
str = rows[i].getElementsByTagName('td')[k].innerHTML;
//ExcelSheet.Cells(i + 1, k + 1).Value = myTable.rows[i].cells[k].innerText;
ExcelSheet.Cells(i + 1, targetCol).Value = myTable.rows[i].cells[k].innerText;
targetCol += 1;
}
}
ExcelSheet.Range("A" + i, "Z" + i).WrapText = true;
ExcelSheet.Range("A" + 1, "Z" + i).EntireColumn.AutoFit();
}
//ExcelSheet.SaveAs("C:\\TEST.XLS");
//ExcelSheet.Application.Quit();
});

Categories

Resources