how to pass html table values to excel sheet cells - javascript

function toExcel(tableID)
{
var detailsTable = document.getElementById(tableID);
var oExcel = new ActiveXObject("Scripting.FileSystemObject");
var oBook = oExcel.Workbooks.Add;
var oSheet = oBook.Worksheets(1);
for (var y=0;y<detailsTable.rows.length;y++)
{
for (var x=0;x<detailsTable.rows(y).cells.length;x++)
{
oSheet.Cells(y+1,x+1) =detailsTable.rows(y).cells(x).innerText;
}
}
oExcel.Visible = true;
oExcel.UserControl = true;
}

As I posted here. However, can't test it myself. So let me know, if it works :)
<html>
<head>
<script type="text/javascript">
function CreateExcelSheet() {
var x = myTable.rows;
var xls = new ActiveXObject("Excel.Application");
xls.visible = true;
xls.Workbooks.Add;
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="CreateExcelSheet()" value="Create Excel Sheet">
</form>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Shivani</td>
<td>25</td>
</tr>
<tr>
<td>Naren </td>
<td>28</td>
</tr>
<tr>
<td>Logs</td>
<td>57</td>
</tr>
<tr>
<td>Kas</td>
<td>54</td>
</tr>
<tr>
<td>Sent</td>
<td>26</td>
</tr>
<tr>
<td>Bruce</td>
<td>7</td>
</tr>
</table>
</body>
</html>

<script language="javascript">
function runApp()
{
var Excel, Book;
var x=myTable.rows;
Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Book = Excel.Workbooks.Add();
for (i = 0; i < x.length; i++)
{
var y = x[i].cells;
for (j = 0; j < y.length; j++)
{
Book.ActiveSheet.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
And the HTML CODE
<table id="myTable">
....
</table>
<form>
<input type="button" onclick="runApp()" value="Export">
</form>
This should do the job.

Related

Retrieve html table contents of TD anchor with Javascript

I can not understand how to grab for example href attribute inside table row cell. When I'm trying to do that it seems that second loop does not work for selected TR elements
function asd(){
this.container = document.getElementsByClassName("cart-contents")[0];
if (!this.container){
return false;
}
this.itemsContainer =
this.container.getElementsByClassName("minicart-table")[0];
this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
this.cartDetails = [];
for (var i = 0, row; row = this.itemsTable.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
console.log(col[0].getElementsByTagName("a")[0].getAttribute("href"));
}
console.log('________________');
}
}
asd();
<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image">text</td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>
Use col instead col[0]
function asd(){
this.container = document.getElementsByClassName("cart-contents")[0];
if (!this.container){
return false;
}
this.itemsContainer =
this.container.getElementsByClassName("minicart-table")[0];
this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
this.cartDetails = [];
for (var i = 0, row; row = this.itemsTable.rows[i]; i++) {
// only the first column
col = row.cells[0];
var anchor = col.getElementsByTagName("a")[0];
if (anchor !== undefined) {
console.log(anchor.getAttribute("href"));
}
console.log('________________');
}
}
asd();
<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image">text</td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>
Use querySelector() for that. It is safe to use. Example:
var anchor = document.querySelector(".cart-contents a:first-child");
console.log(anchor.getAttribute("href"));
<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image">text</td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>
Also, here is how to fix your code:
for (var i = 0, row; row = this.itemsTable.rows; i++) {
for (var j = 0, col; col = row[i].cells; j++) {
console.log(col[j].getElementsByTagName("a")[0].getAttribute("href"));
}
}

Why my javascript throws function not defined error?

Just started JS.
I have a button and it calls a function which should loop through an array and show me each item but it doesn't. It says that:
showWorthSum() function is not defined.
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
var row1= table1.insertRow(rowCount1);
var arr= [];
for(count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(int count = 0; count < arrCount; count++)
{
//totalWorth= totalWorth+ returnedArr[count];
document.write(returnedArr[count]);
//debugger;
}
//return totalWorth;
}
Button:
<button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
And yes I have taken care of script tags etc, just stripped those for the purpose of posting.
Update: (Full code)
<!DOCTYPE html>
<html>
<head>
<link href="css/basic.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script>
function alterTable()
{
//Textboxes code
var tBoxCompany= document.getElementById("txtboxCompany");
var tBoxAmount= document.getElementById("txtboxAmount");
//table code
var table= document.getElementById("tableNetWorths");
var rowCount= table.rows.length;
var row= table.insertRow(rowCount);
var Cell1= row.insertCell(0);
var Cell2= row.insertCell(1);
Cell1.innerHTML= tBoxCompany.value;
Cell2.innerHTML= tBoxAmount.value;
}
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
var row1= table1.insertRow(rowCount1);
var arr= [];
for(count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(int count = 0; count < arrCount; count++)
{
//totalWorth= totalWorth+ returnedArr[count];
document.write(returnedArr[count]);
//debugger;
}
//return totalWorth;
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<table id="tableNetWorths">
<tr>
<th>Company</th>
<th>Net Worth ($)</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>100</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>200</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>344</td>
</tr>
<tr>
<td>Island Trading</td>
<td>22</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>122</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>99</td>
</tr>
</table>
</div>
</div>
<div class="row">
<br>
<div class="col-md-3">
<input type="text" id="txtboxCompany" class="form-control"/>
</div>
<div class="col-md-3">
<input type="text" id="txtboxAmount" class="form-control"/>
</div>
<div class="col-md-3">
<button class="btn btn-primary" onclick="alterTable()" type="button">Add Rows</button>
</div>
<div class="col-md-3">
<button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
</div>
</div>
</div>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
Update: (ShowWorthSum function modified, still not working)
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(count = 0; count < arrCount; count++)
{
totalWorth= totalWorth+ returnedArr[count];
}
return totalWorth;
}
The problem is that you re not defining your variable count. Use this :
for(var count = 0; count < arrCount; count++){ ...
And with JS, no matter if your var is a string or an int, you allways declare your variable using var
remove 'int' from your for loop definition. You have:
for(int count = 0; count < arrCount; count++)
you need:
for(count = 0; count < arrCount; count++)
Also, your loop will return a series of 'undefined' results as it iterates past the number of elements in your actual array. You have six elements, you're looping a fixed 10 times. So once you get past the 6th element, all the rest return (correctly) as undefined.

why my javascript code dosen't work(about search and filter bar)

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>a1</title>
<link rel="stylesheet" href="a1.css" />
<script src="a1.js"></script>
</head>
<body>
<form id = "gallary" method="get" action="">
<div id="searchBox">
<input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>
<select name="genre" id ="filterBar">
<option>Genre</option>
<option>Baroque</option>
<option>Mannerism</option>
<option>Neo-classicism</option>
<option>Realisim</option>
<option>Romanticism</option>
</select>
<input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()" />
</div>
</form>
<div id="artistBox">
<table>
<caption>Paintings</caption>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Artist</th>
<th>Year</th>
<th>Genre</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="05030.jpg"/></td>
<td>Death of Marat</td>
<td>David, Jacques-Louis</td>
<td>1793</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="120010.jpg"/></td>
<td>Potrait of Eleanor of Toledo</td>
<td>Bronzino, Agnolo</td>
<td>1545</td>
<td>Mannerism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="07020.jpg"/></td>
<td>Liberty leading the people</td>
<td>Delacroix, Eugene</td>
<td>1830</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="13030.jpg"/></td>
<td>Arrangement in Grey and Black</td>
<td>Whistler, James Abbott</td>
<td>1871</td>
<td>Realisim</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="06010.jpg"/></td>
<td>Mademoiselle Caroline Riviere</td>
<td>Ingres, Jean-Auguste</td>
<td>1806</td>
<td>Neo-classicism</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
enter code here
above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).
I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;
var filter = document.getElementById("filterBar").value;
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[1];
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script. These get evaluated when the script is loaded but destroyed when the the script file is finished loading. That is the "searchFunction" does not know about the values of these tags.
Consider the updated code: (see it in action at: Plunker)
<script type="text/javascript">
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
console.log(input);
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
var filter = document.getElementById("filterBar").value;
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
} // <-- Missing
}
</script>

How to get input text from table data

I made a table for the user input I've provided some textfield's so it can fill up the table. What I want to do I just want the user to fill up the table and let this save as pdf this will not create a records or insert in the database.
I just want totally save as pdf. But unfortunately when I <input type="text" class="form-control"> insert this in table data <td></td>. The value of the cell become this <input type="text" class="form-control">.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-success" id = "downloadPDF">Download as PDF</button>
</div>
Script:
function tableToJson(table)
{
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++)
{
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length; i++)
{
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++)
{
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF()
{
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1','pt','letter',true);
doc.cellInitialize();
$.each(table, function(i, row)
{
$.each(row, function(j, cell)
{
if(j == "#description" | j == 0)
{
doc.cell(1,10,190,20,cell,i);
}
else
{
doc.cell(1,10,90,20,cell,i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function ()
{
$("#downloadPDF").click(function ()
{
javascript:genPDF();
});
});
Sample JFiddle:
$(document).ready(function() {
$("#addMore").click(function() {
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function() {
if ($('#customFields tbody tr').length == 1) {
} else {
$('#customFields tr:last').remove();
}
});
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF() {
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1', 'pt', 'letter', true);
doc.cellInitialize();
$.each(table, function(i, row) {
$.each(row, function(j, cell) {
if (j == "#description" | j == 0) {
doc.cell(1, 10, 190, 20, cell, i);
} else {
doc.cell(1, 10, 90, 20, cell, i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function() {
$("#downloadPDF").click(function() {
javascript: genPDF();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
<table class="table" id="customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class="description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary" id="addMore">+ Add</button>
<button type="submit" class="btn btn-danger" id="removeRow">- Remove</button>
<button type="submit" class="btn btn-success" id="downloadPDF">Download as PDF</button>
</div>
Cheers
Could loop through all the cells with <input> and replace those with their values before serializing the table to json
$('td:has(input)').text(function(){
return $(this).find('input').val();
});

Javascript writing into Table not working

I just decided to code a little html file which should create a multiplication table with integers from "start" to "end". Start and End are set before in a HTMl Form...
I can give 2 numbers as input and the tr and td elements are create but accessing them by ClassName and filling them with innerHTML does somehow not work.
Here is the Code:
<html>
<head>
<title>Das groà ¥ 1x1</title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function malnehmen(Wert1, Wert2) {
Ausgabe = Wert1 * Wert2;
return Ausgabe;
}
function tabelle() {
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(i = start; i < end+1; i++) {
Reihe = document.createElement("tr");
att = document.createAttribute("class");
att.value = i + "a";
Reihe.setAttributeNode(att);
document.getElementById("Darein").appendChild(Reihe);
for(ii = start; ii < end+1; ii++) {
Feld = document.createElement("td");
att2 = document.createAttribute("class");
att2.value = malnehmen(i, ii);
Feld.setAttributeNode(att2);
Reihe.appendChild(Feld);
}
}
}
function ausfuellen() {
tabelle();
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(a = start; a < end+1; a++) {
alert("Hier denn?");
document.getElementsByClassName(a + "a").innerHTML = a.toString();
for(aa = start; aa < end+1; aa++) {
multi = malnehmen(a, aa);
alert("Angekommen");
document.getElementsByClassName(multi).innerHTML = multi.toString();
}
}
}
</script>
<body>
<FORM name="printer">
<TABLE>
<tr>
<td>Beginnt bei:</td>
<td>
<input type="number" name="anfang" size="3">
</td>
</tr>
<tr>
<td>Endet bei:</td>
<td>
<input type="number" name="ende" size="3">
</td>
</tr>
<tr>
<td>
<input type="button" name="wassolldas" value="Erstellen" onclick="javascript: tabelle();">
</td>
</tr>
</TABLE>
</FORM>
<br>
<TABLE id="Darein" border="1">
</TABLE>
</body>
Does anybody know what I did wrong?
I built in 2 alerts just to see if the javascript part reaches the for loop but there is no pop up in browser.

Categories