How to export multiple HTML tables into a single excel file, along with the html table's css/style? - html

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

Related

Download html table when clicked on button

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>

Want to add Different colors to Different Dynamic ids in a table

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.

How to bind guid on table ng repeat using angularJs

by using following code am generating Guid
//sal urn
$scope.getGUIDSal = function () {
var d = new Date().getTime();
var uuid = 'xxxx-xxxx-4xxx-yxxx-xxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
$scope.URN = $scope.getGUIDSal();
this is my table grid, if multiple rows created i want create new guid for each row ,
<table >
<thead>
<tr>
<th>SNo</th>
<th>URN</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="sal in SalaryDetails">
<td class="label-center">
{{$index + 1}}
</td>
<td>
{{URN}}
</td>
<td>
{{sal.Amount}}
</td>
</tr>
</tbody>
</table>
by using above code am binding same guid for each row
You just need to tweak the code little bit
$scope.getGUIDSal = function () {
var d = new Date().getTime();
var uuid = 'xxxx-xxxx-4xxx-yxxx-xxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
//$scope.URN = $scope.getGUIDSal(); //remove this
And inside view you can do this
<td>
{{getGUIDSal()}}
</td>
If this doesn't work, you can initialize a new scope variable inside getGUIDSal () and use it inside view.
Instead of return uuid;
you can do:
$scope.URN = uuid;
And use $scope.URN inside view
You can pass the id of the salary to the function and generate guiid and return to the view.
HTML
<tr ng-repeat="sal in SalaryDetails">
<td class="label-center">
{{$index + 1}}
</td>
<td>
{{getGUIDSal(passid)}}
</td>
<td>
{{sal.Amount}}
</td>
</tr>
Controller
$scope.getGUIDSal = function (someid) {
var d = new Date().getTime();
var uuid = 'xxxx-xxxx-4xxx-yxxx-xxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
You can do this:
<td>
{{ getGUIDSal() }}
</td>
Just another approach using directive (Run code snippet):
(function() {
var app = angular.module("app", []);
function HomeController() {
var vm = this;
vm.salaryDetails = [{
amount: "$1500"
}, {
amount: "$2000"
}, {
amount: "$5100"
}];
}
app.controller("HomeController", [HomeController]);
function urn() {
return {
restrict: "A",
link: function(scope, element, attrs) {
var d = new Date().getTime();
var uuid = 'xxxx-xxxx-4xxx-yxxx-xxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
element.html(uuid);
//In case you want to add as attribute of td
element.attr("urn",uuid);
}
}
}
app.directive("urn", [urn]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div class="container" ng-controller="HomeController as homeCtrl">
<table>
<thead>
<tr>
<th>SNo</th>
<th>URN</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="sal in homeCtrl.salaryDetails">
<td class="label-center">{{$index + 1}}</td>
<td urn></td>
<td> {{sal.amount}}</td>
</tr>
</tbody>
</table>
</div>
</div>

Google App Script parse table from messed html

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

How to get the column index of particular value of td in HTML tables

Hi there,
I created an HTML table and what I need is to find the column index of a particular value,
but I don't know how to access each value of a table. That is why I am unable to get the index of the column.
Here is my table.
<table>
<tr>
<td>01</td>
<td>02</td>
<td>03</td>
</tr>
<tr>
<td>04</td>
<td>05</td>
<td>06</td>
</tr>
<tr>
<td>07</td>
<td>08</td>
<td>09</td>
</tr>
</table>
and I want the index of the value 03.
The following is a working code, first traverse the table to get the values in this, then compare with your required value and find the index of it..,
<html>
<head>
<script>
function cellvalues() {
var table = document.getElementById('mytable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var hi=table.rows[r].cells[c].innerHTML;
if(hi==03)
{
alert(table.rows[r].cells[c].cellIndex);
}
}
}
}
</script>
</head>
<body>
<table id="mytable">
<tr><td>01</td><td>02</td><td>03</td>
</tr>
<tr><td>04</td><td>05</td><td>06</td>
</tr>
<tr><td>07</td><td>08</td><td>09</td>
</tr>
</table>
<input type="button" onclick=cellvalues()>
</body>
</html>
You can try this (untested)
var tab = document.getElementsByTagName("table")[0];
var tr = tab.childNodes;
for (var i = 0; i < tr.length; i++) {
var td = tr[i].childNodes;
for (var j = 0; j < tr.length; j++) {
if (td[j].innerHTML == "03") {
alert(i + "," + j);
}
}
}
I suggest using jQuery index for this:
var trCollection = $('table tr');
$('table td').each(function () {
console.log(trCollection.index($(this).parent()));
});