is there a way remove all childnode <br> inside document - javascript

I found a code example online, about how to convert HTML table into CSV. The code seems fine.
https://jsfiddle.net/3p0r2haq/12/
function download_csv(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;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, 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);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
document.querySelector("button").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
However, the document has node <br>, which will mass up str. I added an example here. My question is how to avoid the <br> node or remove them all before query?
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Geronimo</td>
<td>26</td>
<td><br>France</td>
</tr>
<tr>
<td>Natalia</td>
<td>19</td>
<td>Spain</td>
</tr>
<tr>
<td>Silvia</td>
<td>32</td>
<td>Russia</td>
</tr>
</tbody>
</table>
So the result will mass up like the image

Just change
row.push(cols[j].innerText);
To
row.push(cols[j].innerText.trim());
Using trim() will remove the \n and any other whitespace in a cell
function export_table_to_csv(html, 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.trim());
csv.push(row.join(","));
}
// Download CSV
// download_csv(csv.join("\n"), filename);
// log results for demo instead of download
console.log(csv)
}
export_table_to_csv()
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
<tr>
<td>Geronimo</td>
<td>26</td>
<td><br>France</td>
</tr>
<tr>
<td>Natalia</td>
<td>19</td>
<td>Spain</td>
</tr>
<tr>
<td>Silvia</td>
<td>32</td>
<td>Russia</td>
</tr>
</tbody>
</table>

Related

Pound symbol (£) encoding issue while converting an HTML table into CSV using JavaScript

I am using pound symbol(£) in table head(th) and i am exporting the table in CSV format using javascript. But the CSV file is showing the pound(£) symbol like "£".
I tried various solutions provided in SO threads. But none of them worked for me.
How can I fix this issue?
Below is the code of the table:
<thead>
<tr>
<th>Property Name</th >
<th>Description</th >
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead
I am using the below JavaScript function to export the table into CSV.
function exportTableToCSV(filename,userName) {
var csv = [];
var rows = document.querySelectorAll("table#"+userName+" 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(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
The output is like the one in the below screenshot.
Can you replace js and check.
function exportTableToCSV(filename, userName) {
var csv = [];
var rows = document.querySelectorAll("table#" + userName + " 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(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
var csvString = csv;
var universalBOM = "\uFEFF";
var a = window.document.createElement('a');
a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(universalBOM + csvString));
a.setAttribute('download', filename);
window.document.body.appendChild(a);
a.click();
}
exportTableToCSV('test.csv', 'velu');
<table id="velu">
<thead>
<tr>
<th>Property Name</th>
<th>Description</th>
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead>
</table>

Preserve a Leading Zero When Exporting HTML Table To CSV With JavaScript

The following DEMO allows you to export the HTML Table as CSV by clicking "Export to CSV" button.
However, if you look at the exported CSV you'll notice that in the last row:
"00001" get truncated to just "1"
function download_csv(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;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, 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);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
document.querySelector("#button2").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
<table border="1px">
<thead>
<tr>
<th>ID</th>
<th>PROVINCE</th>
<th>DIVISION</th>
<th>NAME</th>
</tr>
</thead>
<tbody>
<tr><td>76363</td><td>Province1</td><td>AA</td><td>NAME1</td></tr>
<tr><td>76371</td><td>Province2</td><td>AB</td><td>NAME2</td></tr>
<tr><td>76388</td><td>Province3</td><td>AC</td><td>NAME3</td></tr>
<tr><td>76424</td><td>Province4</td><td>AD</td><td>NAME4</td></tr>
<tr><td>00001</td><td>undefined</td><td>undefined</td><td>undefined</td>
</tr>
</tbody>
</table>
<button id="button2">Export to CSV</button>
I want to preserve the leading zeroes with any data I might put in the table.
The only way to do that is by adding an apostrophe ' BEFORE the number that starts with 0.
In other words: 00001 will turn to '00001
I am assuming the solution is to add an:
IF <td> starts with 0 add ' statement.
How to do that?
function download_csv(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;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, 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[0]=='0' ? ("'" + cols[j].innerText) : cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
document.querySelector("#button2").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
<table border="1px">
<thead>
<tr>
<th>ID</th>
<th>PROVINCE</th>
<th>DIVISION</th>
<th>NAME</th>
</tr>
</thead>
<tbody>
<tr><td>76363</td><td>Province1</td><td>AA</td><td>NAME1</td></tr>
<tr><td>76371</td><td>Province2</td><td>AB</td><td>NAME2</td></tr>
<tr><td>76388</td><td>Province3</td><td>AC</td><td>NAME3</td></tr>
<tr><td>76424</td><td>Province4</td><td>AD</td><td>NAME4</td></tr>
<tr><td>00001</td><td>undefined</td><td>undefined</td><td>undefined</td>
</tr>
</tbody>
</table>
<button id="button2">Export to CSV</button>
When opening the file with Excel, or any other tabular type program, the column will be interpreted as a number and leading zeros are removed.
If you open the file in raw format though, in Notepad for example, or tell Excel to interpret the column as text, you'll see the leading zeros.
People using your exported CSV will probably know this.

How to save Html table data in .txt file?

This is my Html Table.
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Id</th>
<th>Phone Number</th>
<th>Prefered Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>Miles</td>
<td>james#abcd.com</td>
<td>9876543210</td>
<td>email</td>
</tr>
<tr>
<td>John</td>
<td>Paul</td>
<td>john#abcd.com</td>
<td>9638527410</td>
<td>phone</td>
</tr>
<tr>
<td>Math</td>
<td>willams</td>
<td>Math#abcd.com</td>
<td>99873210456</td>
<td>phone</td>
</tr>
</tbody>
</table>
In this table there is Save Button.
<input type="button" id="txt" value="Save" />
Button Code
function tableToJson(table) {
var data=[];
var headers=[];
for (var i=0;
i < table.rows[0].cells.length;
i++) {
headers[i]=table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
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;
}
When the click the save button, The html table data will stored in the .txt document without <table>,<tr>,<td>. The data storing format will be like below format.
(James,Miles,james#abcd.com,9876543210,email),
(John,Paul,john#abcd.com,9638527410,phone),
(Math,willams,Math#abcd.com,99873210456,phone)
Slightly clearer code than the above answer that works for any number of columns
var retContent = [];
var retString = '';
$('tbody tr').each(function (idx, elem)
{
var elemText = [];
$(elem).children('td').each(function (childIdx, childElem)
{
elemText.push($(childElem).text());
});
retContent.push(`(${elemText.join(',')})`);
});
retString = retContent.join(',\r\n');
jsfiddle with the full code
First of all, you have to create data which contains all user details.
userDetails='';
$('table tbody tr').each(function(){
var detail='(';
$(this).find('td').each(function(){
detail+=$(this).html()+',';
});
detail=detail.substring(0,detail.length-1);
detail+=')';
userDetails+=detail+"\r\n";
});
Then you need to save file:
var a=document.getElementById('save');
a.onclick=function(){
var a = document.getElementById("save");
var file = new Blob([userDetails], {type: 'text/plain'});
a.href = URL.createObjectURL(file);
a.download = "data.txt";
}
Here is a working solution: jsfiddle.

Appending rows to table using loop ( Javascript )

I have a two webpages. eventsCreated and createAnEvent. In createAnEvent, a form is used to allow users' inputs. The inputs are then stored to local storage with the following function:
document.addEventListener("DOMContentLoaded",docIsReady);
var createEvent;
function docIsReady(){
createEvent=localStorage.getItem("createEvent");
if (createEvent==null){
CreateEvent=[];
}
else {
createEvent=JSON.parse(createEvent);
}
}
function saveToStorage() {
var one;
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
localStorage["X"]=JSON.stringify(positions);
var r=localStorage["X"];
r=JSON.parse(r);
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
one={"name":nameofevent,"pos":r,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
createEvent.push(one);
localStorage.setItem("createEvent",JSON.stringify(createEvent));
//alert(JSON.stringifys(one));
//alert(one.pos[0]); //to get one position
return false;
}
I made createEvent an array so as to store the multiple inputs because there cannot be only one event created. In the eventsCreated page, I need to display the user inputs in a table that looks something like this :
<table border="1px" id="list">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</table>
I am not sure how to use javascript to get the event details that the user has entered in the createAnEvent page and display it in the table.
This is the javascript:
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i=0; i<one.length; i++) {
var row = table.insertRow(i);
for (var j=0; j<=6; j++) {
var cell = row.insertCell(j);
}
cell[0].innerHTML = "one[0]";
cell[1].innerHTML = "one[1]";
cell[2].innerHTML = "one[1]";
cell[3].innerHTML = "one[3]";
cell[4].innerHTML = "one[4]";
cell[5].innerHTML = "one[5]";
cell[6].innerHTML = "one[6]";
}
}
I would use jquery to add elements to your page.
But you can use the dom if you like.
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i = 0; i < one.length; i++) {
var this_tr = document.createElement("tr");
for (var j=0; j < one[i].length; j++) {
var this_td = document.createElement("td");
var text = document.createTextNode(one[i][j]);
this_td.appendChild(text);
this_tr.appendChild(this_td);
}
table.appendChild(this_tr);
}
This should work for you or close to it. You table is also wrong please correct it to this.
<table border="1px">
<thead>
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</thead>
<tbody id="list">
</tbody>
</table>
See for examples:
http://www.w3schools.com/jsref/met_node_appendchild.asp

How to export html table to excel using javascript

My table is in format
<table id="mytable">
<thead>
<tr>
<th>name</th>
<th>place</th>
</tr>
</thead>
<tbody>
<tr>
<td>adfas</td>
<td>asdfasf</td>
</tr>
</tbody>
</table>
I found the following code online. But it doesn't work if i use "thead" and "tbody" tags
function write_to_excel() {
str = "";
var mytable = document.getElementsByTagName("table")[0];
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i + 1, j + 1).Value = str;
}
}
Check https://github.com/linways/table-to-excel.
Its a wrapper for exceljs/exceljs to export html tables to xlsx.
TableToExcel.convert(document.getElementById("simpleTable1"));
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel#v1.0.4/dist/tableToExcel.js"></script>
<table id="simpleTable1" data-cols-width="70,15,10">
<tbody>
<tr>
<td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">
Sample Excel
</td>
</tr>
<tr>
<td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">
Italic and horizontal center in Arial
</td>
</tr>
<tr>
<th data-a-text-rotation="90">Col 1 (number)</th>
<th data-a-text-rotation="vertical">Col 2</th>
<th data-a-wrap="true">Wrapped Text</th>
<th data-a-text-rotation="-45">Col 4 (date)</th>
<th data-a-text-rotation="-90">Col 5</th>
</tr>
<tr>
<td rowspan="1" data-t="n">1</td>
<td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">
ABC1
</td>
<td rowspan="1" data-f-strike="true">Striked Text</td>
<td data-t="d">05-20-2018</td>
<td data-t="n" data-num-fmt="$ 0.00">2210.00</td>
</tr>
<tr>
<td rowspan="2" data-t="n">2</td>
<td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">
ABC 2
</td>
<td rowspan="2" data-a-indent="3">Merged cell</td>
<td data-t="d">05-21-2018</td>
<td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>
</tr>
<tr>
<td data-t="d">05-22-2018</td>
<td data-t="n" data-num-fmt="$ 0.00">2493.00</td>
</tr>
<tr>
<td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">
<b>Hyperlink</b>
</td>
<td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">
<b>4933.00</b>
</td>
</tr>
<tr>
<td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">
مرحبا
</td>
<td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">
<b>2009.00</b>
</td>
</tr>
<tr>
<td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>
</tr>
<tr>
<td data-t="b">true</td>
<td data-t="b">false</td>
<td data-t="b">1</td>
<td data-t="b">0</td>
<td data-error="#VALUE!">Value Error</td>
</tr>
<tr>
<td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">
All borders separately
</td>
</tr>
<tr data-exclude="true">
<td>Excluded row</td>
<td>Something</td>
</tr>
<tr>
<td>Included Cell</td>
<td data-exclude="true">Excluded Cell</td>
<td>Included Cell</td>
</tr>
</tbody>
</table>
This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.
Only works in Mozilla, Chrome and Safari..
$(function() {
$('button').click(function() {
var url = 'data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html())
location.href = url
return false
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</script>
<button>click me</button>
<div id="tableWrap">
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
The reason the solution you found on the internet is no working is because of the line that starts var colCount. The variable mytable only has two elements being <thead> and <tbody>. The var colCount line is looking for all the elements within mytable that are <tr>. The best thing you can do is give an id to your <thead> and <tbody> and then grab all the values based on that. Say you had <thead id='headers'> :
function write_headers_to_excel()
{
str="";
var myTableHead = document.getElementById('headers');
var rowCount = myTableHead.rows.length;
var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
}
and then do the same thing for the <tbody> tag.
EDIT: I would also highly recommend using jQuery. It would shorten this up to:
function write_to_excel()
{
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
$('th, td').each(function(i){
ExcelSheet.ActiveSheet.Cells(i+1,i+1).Value = this.innerHTML;
});
}
Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.
EDIT: To answer your question about how to do this for n number of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:
var tables = document.getElementsByTagName('table');
for(var i = 0; i < tables.length; i++)
{
write_headers_to_excel(tables[i]);
write_bodies_to_excel(tables[i]);
}
Then change the function write_headers_to_excel() to function write_headers_to_excel(table). Then change var myTableHead = document.getElementById('headers'); to var myTableHead = table.getElementsByTagName('thead')[0];. Same with your write_bodies_to_excel() or however you want to set that up.
Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just Create a blank iframe
enter code here
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on
<button id="btnExport" onclick="fnExcelReport();"> EXPORT
</button>
This might be a better answer copied from this question.
<script type="text/javascript">
function generate_excel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}
function base64_encode (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafal Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
</script>
function XLExport() {
try {
var i;
var j;
var mycell;
var tableID = "tblInnerHTML";
var objXL = new ActiveXObject("Excel.Application");
var objWB = objXL.Workbooks.Add();
var objWS = objWB.ActiveSheet;
for (i = 0; i < document.getElementById('<%= tblAuditReport.ClientID %>').rows.length; i++) {
for (j = 0; j < document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells.length; j++) {
mycell = document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells(j);
objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
}
}
//objWS.Range("A1", "L1").Font.Bold = true;
objWS.Range("A1", "Z1").EntireColumn.AutoFit();
//objWS.Range("C1", "C1").ColumnWidth = 50;
objXL.Visible = true;
}
catch (err) {
}
}
Check this out... I just got this working and it seems exactly what you are trying to do as well.
2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
range.execCommand("Copy");
}
function write_to_excel()
{
var tableID = "AllItems";
selectElementContents( document.getElementById(tableID) );
var excel = new ActiveXObject("Excel.Application");
// excel.Application.Visible = true;
var wb=excel.WorkBooks.Add();
var ws=wb.Sheets("Sheet1");
ws.Cells(1,1).Select;
ws.Paste;
ws.DrawingObjects.Delete;
ws.Range("A1").Select
excel.Application.Visible = true;
}
Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)
I think you can also think of alternative architectures. Sometimes something can be done in another way much more easier. If the producer of HTML file is you, then you can write an HTTP handler to create an Excel document on the server (which is much more easier than in JavaScript) and send a file to the client. If you receive that HTML file from somewhere (like an HTML version of a report), then you still can use a server side language like C# or PHP to create the Excel file still very easily. I mean, you may have other ways too. :)
I would suggest using a different approach. Add a button on the webpage that will copy the content of the table to the clipboard, with TAB chars between columns and newlines between rows. This way the "paste" function in Excel should work correctly and your web application will also work with many browsers and on many operating systems (linux, mac, mobile) and users will be able to use the data also with other spreadsheets or word processing programs.
The only tricky part is to copy to the clipboard because many browsers are security obsessed on this. A solution is to prepare the data already selected in a textarea, and show it to the user in a modal dialog box where you tell the user to copy the text (some will need to type Ctrl-C, others Command-c, others will use a "long touch" or a popup menu).
It would be nicer to have a standard copy-to-clipboard function that possibly requests a user confirmation... but this is not the case, unfortunately.
I try this with jquery;
use this and have fun :D
jQuery.printInExcel = function (DivID)
{
var ExcelApp = new ActiveXObject("Excel.Application");
ExcelApp.Workbooks.Add;
ExcelApp.visible = true;
var str = "";
var tblcount = 0;
var trcount = 0;
$("#" + DivID + " table").each(function ()
{ $(this).find("tr").each(function ()
{ var tdcount = 0; $(this).find("td").each(function ()
{ str = str + $(this).text(); ExcelApp.Cells(trcount + 1, tdcount + 1).Value = str;
str = ""; tdcount++
});
trcount++
}); tblcount++
});
};
use this in your class and call it with $.printInExcel(your var);
function exportExcelFromTable(){
let table = document.getElementById('tableId');
console.log(table);
TableToExcel.convert(table, {
name: `export.xlsx`,
sheet: {
name: 'Exported_Data' // sheetName
}
});
}
exportTable() {
if (this.arrayname.length >= 1) { //here your array name which are display in table
$('#exportable tr td').css('text-align', 'center'); //table formating
const downloadLink = document.createElement('a');
const table = document.getElementById('exportable');
const tableHTML = table.outerHTML.replace(/ /g, '%20');
var html = table.outerHTML;
var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url
downloadLink.href = 'data:' + url + ' ';
downloadLink.download = 'tablename.xls'
downloadLink.click();
} else {
alert('table is empty')
}}
` //table tab should be like this <table class="table class" id="exportable" border="1" style="border-collapse: collapse;">
//button <button class="btn btn-xs btn-primary "(click)="exportTable();">
<i class="fa fa-file-excel-o m-right-5"></i>
<span>Export Excel</span>
</button>

Categories