I am trying to download the contents in the html table. Can anyone help me download its contents when clicked on button. I tried with following code but not working.
function exportTableToCSV(filename) {
alert("I am an alert box!");
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);
csv.push(row.join(","));
}
// Download CSV file
alert('Hey')
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();
}
<table border=1><button onclick="exportTableToCSV(\'members.csv\');">Export HTML Table To CSV File</button>
<tr>
<th></th>
<th> sub_domain</th>
<th> nReviews</th>
<th> Ratings_e</th>
<th> Text_e</th>
<th> rn</th>
</tr>
<tr>
<td align=\ "right\"> 1</td>
<td> a1</td>
<td align=\ "right\"> 2</td>
<td> 1, 2</td>
<td> asd, dfdsf</td>
<td align="left"> 1</td>
</tr>
</table>
The filename given format is the issue.
You can replace the button code as follows.
<button onclick="exportTableToCSV('members.csv');">Export HTML Table To CSV File</button>
function exportTableToCSV(filename) {
alert("I am an alert box!");
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);
csv.push(row.join(","));
}
// Download CSV file
alert('Hey')
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();
}
<body>
<table border=1>
<button onclick="exportTableToCSV('members.csv');">Export HTML Table To CSV File</button>
<tr>
<th></th>
<th> sub_domain</th>
<th> nReviews</th>
<th> Ratings_e</th>
<th> Text_e</th>
<th> rn</th>
</tr>
<tr>
<td align=\ "right\"> 1</td>
<td> a1</td>
<td align=\ "right\"> 2</td>
<td> 1, 2</td>
<td> asd, dfdsf</td>
<td align="left"> 1</td>
</tr>
</table>
</body>
Related
I have a problem exporting the paginated table in csv file. It cannot export the whole paginated table, just only export the first paginated table data.
Below is my coding:
HTML
<button onclick="exportTableToCSV('manufacturer_brand.csv')">Export</button>
<table id="table_js" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</thead>
<tfoot>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</tr>
</tfoot>
</table>
Javascript
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();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 1; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 1; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
Export CSV file result like below, just can export first paginated page table, other paginate cannot export:
Below is my table, actually I have a total of 7 paginated pages in the table
How someone can guide me on how to export paginate table in a CSV file.
I know there are a lot of this type of question in this site, but i cant find any working solution for this that suit my need. What i need is
1. export multiple html table to excel
2. the table in the excel look exactly like the html table (the css, styling are the same. e.g background-color)
Is there any way to do this using javascript,etc.?
I found one question for this problem here, but the solution shown there did not solve the css problem. Means that the excel table not have the css like the html table (e.g The excel table doesnt have yellow background eventhough the html table have it)
So basically the main problem is I need the format for the excel file to be same as the html table (css,etc.). Sorry I am new to programming..
Here you can access the jsfiddle. Or if the link doesnt work, you can just try it below (The codes are taken from the original post , but with an addition of a simple yellow-colored background css in it's tr)Thanks in advance.
var tablesToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
+ '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
+ '<Styles>'
+ '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
+ '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
+ '</Styles>'
+ '{worksheets}</Workbook>'
, tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
, tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(tables, wsnames, wbname, appname) {
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += '<Row>'
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
ctx = { attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
, nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
, data: (dataFormula)?'':dataValue
, attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += '</Row>'
}
ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
workbookXML = format(tmplWorkbookXML, ctx);
console.log(workbookXML);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();
<table id="tbl1" class="table2excel">
<tr style="background-color:yellow;">
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>1
</td>
<td>2
</td>
<td>3
</td>
</tr>
<tr>
<td>Butter</td>
<td>4
</td>
<td>5
</td>
<td >6
</td>
</tr>
</table>
<hr>
<table id="tbl2" class="table2excel">
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>7
</td>
<td>8
</td>
<td>9
</td>
</tr>
<tr>
<td>Butter</td>
<td>14
</td>
<td>15
</td>
<td >16
</td>
</tr>
</table>
<button onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>
Found the solution for this. I use the DataTables. Read more here DataTables forum
I am having some issues on <tr> background color, having the same <tr id="">
Here is my Table.
<table class="table">
<tr id="2552">
<td>Roll No 1</td>
<td>800</td>
</tr>
<tr id="2552">
<td>Roll No 1</td>
<td>700</td>
</tr>
<tr id="4444">
<td>Roll No 11</td>
<td>800</td>
</tr>
<tr id="4444">
<td>Roll No 11</td>
<td>900</td>
</tr>
<tr id="7676">
<td>Roll No 12</td>
<td>800</td>
</tr>
<tr id="7676">
<td>Roll No 12</td>
<td>900</td>
</tr>
</table>
What I want.
Every 2 <tr> have same id But these ids are dynamic.
I want the <tr> having same id get different background-color.
Now in this table there are 3 ids are used. So 3 different colors can be there.
I have applied many jquery codes but failed.
Please help me
I Developed Dynamic table row id based color set and i hope its solve your problem. Code Reference
var table = document.getElementsByTagName("table")[0];
var secondRow = table.rows[1];
var count=0;
var trid =[];
var clr =[];
for(var i=0;i<table.rows.length;i++)
{
trid.push(table.rows[i].id);
}
var uniqueArray = [];
for(i=0; i < trid.length; i++){
if(uniqueArray.indexOf(trid[i]) === -1) {
uniqueArray.push(trid[i]);
}
}
for(var i = 0; i < uniqueArray.length; i++)
{
clr.push('#'+Math.floor(Math.random()*16777215).toString(16));
}
for (var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < uniqueArray.length; j++)
{
if(table.rows[i].id ==uniqueArray[j]){
table.rows[i].style.backgroundColor = clr[j];
}
}
}
Hi Use looping in Jquery, loop through each tr and determine its ID, then apply bg color
$( "tr" ).each(function( index ) {
var ID = $(this)..attr('id');
if(ID == '2221')
{
$(this).css('background-color', 'red');
}
else if(ID == '2223')
{
$(this).css('background-color', 'blue');
}
});
How about something like this?
const used_ids = []
$( "tr" ).each(function( index ) {
const id = $(this).attr.('id')
if (!used_ids.includes(id)) {
// If the id has not been met before, add it to the array.
used_ids.push(id)
}
// Get index of id from array of used ids
const index = used_ids.indexOf(id)
// If index is an even number, set background colour to grey, otherwise white
if (index%2 === 0) $(this).css('background-color', 'white');
else $(this).css('background-color', 'grey');
})
It builds an array of unique ids, then assigns white to those with an even index in the array and grey to the odd indices.
I am havign an issue where there is only one item being shown in my table (usually the most recent bug entered)
could you let me know if there is an error with my code?
Here is it
//Web service call to get the data
var getAllBugsData = $.get("https://m2052626.scm.tees.ac.uk/AST_14/Bugg.ly2/index.php/bug/GetAllBugs",
function(data)
{
var j = 0;
var myTotal = data.length ;
for(var i =0; i < data.length;i++)
{
var item = data[i];
bug_id = item.bug_id;
BugType = item.BugType;
Bugaddress = item.Bugaddress;
admin_id = item.admin_id;
status = item.status;
Description = item.description;
type = item.type;
var bugDetails = '<div class="PropDetails">Bug Id: '+bug_id+'</div><div class="PropDetails">Type of Bug: '+BugType+'</div><div class="PropDetails">Admin Number :'+admin_id+'</div><div class="PropDetails">Type Of Bug: '+type+'</div>';
$('.listAllBugs').append('<tr class="table-stroke"><td>'+bugDetails+'</td><td>Edit</tr>');
And the table code is this
<!--Data Table Goes HERE-->
<table data-role="table" data-mode="reflow" class="ui-responsive table-stroke">
<thead>
<tr>
<th width="100%">Bug Details</th>
</tr>
</thead>
<tbody class="listAllBugs">
</tbody>
</table>
I want to create a script which download html, parse a table and save it to a SpreadSheet. I am stuck on downloading and parsing.
Xpath to table is:
/html/body/table/tbody/tr[5]/td/table/tbody/tr/td[2]/table
Currently I am stuck at parsing Xpath.
function fetchIt() {
var fetchString="http://www.zbranebrymova.com/index.php?s_lev=22&type=nabku*signa"
var response = UrlFetchApp.fetch(fetchString);
var xmlDoc = Xml.parse(response.getBlob().getDataAsString(),true);
var b = xmlDoc.getElement().getElement("body").getElement("table") ;
Logger.log(b);
}
I don't know if this will be helpful, here is a snippet of my table parsing code:
html file FOO.HTM:
<html>
<head> </head>
<body style="margin-left:10px">
<table title="">
<tbody>
<tr>
<th align="center" abbr="Sunday">Sun</th>
<th align="center" abbr="Monday">Mon</th>
</tr>
<tr>
<td align="left"><a title="January 01">1</a>
<div>Joe,Doe</div>
<div>Murphy,Jack</div>
</td>
<td align="left"><a title="January 02">2</a>
<div>Carlson,Carl</div>
<div>Guy,Girl</div>
<div>Lenin,Vladimir</div>
</td>
</tr>
</tbody>
</table>
</body>
<html>
and this is how I parse it:
function foo() {
var page = UrlFetchApp.fetch('foo.htm');
var rows = Xml.parse(page,true).getElement()
.getElement("html")
.getElement("body")
.getElement("table")
.getElement("tbody")
.getElements("tr");
for (var ii = 0; ii < rows.length; ii++) {
var cols = rows[ii].getElements("td");
for (var jj = 0; jj < cols.length; jj++) {
var divs = cols[jj].getElements("div");
for (var kk = 0; kk < divs.length; kk++) {
var div = divs[kk];
}
}
}
}
cheers, sean