I have this html code to enter the starting and ending date ranges
<input id="fechaInicio" type="text"
<input id="fechaFinal" type="text"
<a onclick = "listadoConsulta()" href="#" class="btn"
the javascript code
async function listadoConsulta() {
document.getElementById('fechaInicio').value = date1
document.getElementById('fechaFinal').value = date2
var url = URLSERVIDOR + 'listado/consulta'
var respuesta = await fetch(url, {
"method": 'GET',
"headers":{
"Content-Type": 'application/json'
}
})
listado = await respuesta.json();
var html = ''
for (registro of listado) {
var row = `<tr>
<td>${registro.folio}</td>
<td>${registro.lote}</td>
<td>${registro.tabla}</td>
<td>${registro.cajas}</td>
<td>${registro.peso_neto}</td>
</tr>`
html = html + row;
}
document.querySelector('#tablaFechas> tbody').outerHTML = html
and database query in python
#app.route('/api/listado/consulta')
#cross_origin()
def listadoConsulta():
ejecutarListado = mysql.connection.cursor()
#date1 = "20220920"
#date2 = "20220921"
ejecutarListado.execute('SELECT id, folio, lote, tabla, cajas, peso_neto FROM
`registrocorte` WHERE `fecha` BETWEEN ' + date1 + " AND " + date2 + ';')
datos = ejecutarListado.fetchall()
resultadoLista = []
for fila in datos:
contenido = {'id': fila[0],
'folio': fila[1],
'lote': fila[2],
'tabla': fila[3],
'cajas': fila[4],
'peso_neto': fila[5]
}
resultadoLista.append(contenido)
return jsonify(resultadoLista)
It works well if I put the dates directly in the query in python, the question is how can I make it do the query using the dates that I give to the html?
Assume, Im having a table like below:
I need to drop the "Contact" column and export the remaining column to the CSV file.
HTML:
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
On click of the download button, js function will get called.
JavaScript
//Drop Column
function dropColumn(mytableid){
var clonetable = $('#mytableid').clone();
clonetable.find('td:nth-child(2),(the:nth-child(2)').remove();
download_table_as_csv(clonetable);
}
//Download as CSV
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Error:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
How to export table data to CSV by excluding a specific column?.Any way to achieve this.
Thanks.
If you find a collection of table headers and from that find the cell that contains the exclusion term ( Contact ) in it's textContent you can use that index later to exclude table cells ( per row ) of the same index.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Export HTML table - exclude column by text content or other criteria</title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
const preparetext=function(text,regex,rep){
text=text.replace(/(\r\n|\n|\r)/gm, '');
text=text.replace(/(\s\s)/gm, ' ');
text=text.replace(/"/g, '""');
return text;
};
document.querySelector('input[type="button"][name="export"]').addEventListener('click',e=>{
let table=document.querySelector('table#geronimo');
let colHeaders=table.querySelectorAll('tr th');
let colRows=table.querySelectorAll('tr:not( .headers )');
let index=-1;
let exclude='Contact';
let headers=[];
let data=[];
colHeaders.forEach( ( th, i )=>{
if( th.textContent!=exclude )headers.push( [ '"', preparetext( th.textContent ), '"' ].join('') )
else index=i;
});
data.push( headers.join(',') );
data.push( String.fromCharCode(10) );
if( index > -1 ){
colRows.forEach( tr => {
let cells=tr.querySelectorAll('td');
let row=[];
cells.forEach( ( td, i )=>{
if( i !== index ) row.push( [ '"', preparetext( td.textContent), '"' ].join('') )
});
data.push( row.join(',') );
data.push( String.fromCharCode(10) );
});
let a=document.createElement('a');
a.download='export_'+table.id+'_'+( new Date().toLocaleDateString() )+'.csv';
a.href=URL.createObjectURL( new Blob( data ) );
a.click();
}
})
});
</script>
</head>
<body>
<table id='geronimo'>
<tr class='headers'>
<th scope='col'>Company</th>
<th scope='col'>Contact</th>
<th scope='col'>Country</th>
</tr>
<tr>
<td>Jolly Roger Cookery School Ltd</td>
<td>Blackbeard</td>
<td>Jamaica</td>
</tr>
<tr>
<td>Autonomous Hedgehog Collective</td>
<td>Mr. Ben</td>
<td>United Kingdom</td>
</tr>
<tr>
<td>The Cock Inn</td>
<td>Miss. Tilly Lykes</td>
<td>Scotland</td>
</tr>
<tr>
<td>Hooker Furniture</td>
<td>Hubert</td>
<td>Hanoi</td>
</tr>
<tr>
<td>Horrible Haggis Hunt</td>
<td>Horace Hubert</td>
<td>Hungary</td>
</tr>
</table>
<input type='button' name='export' value='Download CSV' />
</body>
</html>
so i have just started to learn javascript, literally had 2 classes on it. So my knowledge is very very limited. But I am trying to make an appointment application and i keep receiving a Uncaught rangeError :Invalid string length error, and i have no idea why or how to fix it. Basically I have been given some code to copy without much explanation to it, so if anyone can help me with this error it would be greatly appreciated. The code where the error is appearing is below and i believe it is the line table += appt.tableRow(); which is causing the issue. There is obviously more to this code, but not sure if it needs to be given, as the issue is in the showTable function
Edit : I just added the whole javascript code to make it easier
var Appointment = function(subject, description,date, time) {
this.subject = subject;
this.description = description;
this.datetime = new Date(date + " " + time);
this.completed = false;
};
Appointment.prototype.isDue = function(){
var now = new Date();
if(this.datetime > now){
return false;
} else {
return true;
}
};
Appointment.prototype.whenDue = function(){
return this.datetime - new Date();
}
Appointment.prototype.toString = function(){
var s = this.subject +'\n'+
this.datetime.toString() + '\n';
if(this.completed){
s +="Not Completed\n\n";
}
return s
};
Appointment.prototype.howManyDaysTill = function() {
var ms = (this.datetime - new Date()) / 24/60/60/1000
return ms;
};
Appointment.prototype.howManyHoursTill = function () {
var hours = (this.datetime - new Date()) /60/60/1000
return hours;
};
Appointment.prototype.getDate = function() {
return this.datetime.toDateString();
};
Appointment.prototype.getTime = function (){
return (this.datetime.getHours()) + ":" + (this.datetime.getMinutes());
};
Appointment.prototype.tableRow = function(){
var tr = "<tr><td>" + this.getDate() + "</td><td>" +
this.getTime() + "</td><td>" + this.subject +
"</td></tr>";
return tr;
};
var appointments = [];
window.onload = function(){
var newButton = document.getElementById("new");
newButton.onclick = function () {
var subj = prompt("Enter a subject title for the appointment");
var desc = prompt("Enter a description for the appointment");
var date = prompt("Enter the appointment date in the format (e.g) 'Sep
25, 2012");
var time = prompt("Enter the appointment time in the format hh:mm");
var a = new Appointment((subj,desc,date,time));
appointments.push(a);
return showTable();
};
var showTable = function() {
var tableDiv = document.getElementById("table"),
table = "<table border='1'>" +
"<thead><th>Date</th><th>Time</th><th>Subject</th><th>Completed</th>
</thead>";
for (var i = 0, j = appointments.length; i < j; j++) {
var appt = appointments[i];
table += appt.tableRow();
}
table += "</table>";
tableDiv.innerHTML = table;
};
}
HTML5
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="appointments.js"></script>
<title>Appointments</title>
</head>
<body>
<button id="new">New Appointment</button>
<div id ="table"></div>
<header>
<h1>
Appointments Book
</h1>
<p> Enter appointment details and press OK to add, Cancel to revert.</p>
</header>
<table>
<tr>
<td>Subject : </td> <td>input type="text" size="40" id="subject"</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea rows = "5" cols=""50" maxlength="200" id="description">
</textarea>
</td>
</tr>
<tr> <td>Due Date:</td><td><input type ="date" id="duedate"/></td>
</tr>
</table>
<button id = "OK">OK </button><button id = "cancel">Cancel</button>
<hr/>
</body>
</html>
The for loop must increment on i and not on j. The current one is causing a infinite looping and hence the following line is creating a string that is too big to handle by the JS engine and hence the error
table += appt.tableRow();
I want to insert data from an array into a database table in the submit() function where the sql syntax is at. I want to insert the data then redirect to another page after successful. I don't know how to do this with ajax.
I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array.
example:
[{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}]
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
type: "POST",
data: {arr: arr},
url: "next.php",
success: function(){
}
});
/////////////////////////////////
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form action"next.php" method="post">
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
</form>
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str = '<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
//var val = confirm("Are you sure ..?");
//if(val){
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
//}
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
// sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
// mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database
JS
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {arr: JSON.stringify(data)},
url: "next.php",
success: function(){
}
});
}
PHP (next.php)
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $d;
// insert to db
}
Please Keep the following in mind
Javascript/JQuery is client side and hence cannot access the database which is on the server.
You can Send data via AJAX to next.php and then use this data to insert into your database.
To improve debugging, use the following code to ensure the correct data is being delivered in next.php
var_dump($_POST);
Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post).
I have a HTML table in velocity template. I want to export the html table data to excel using either java script or jquery, comatibale with all browser.
I am using below script
<script type="text/javascript">
function ExportToExcel(mytblId){
var htmltable= document.getElementById('my-table-id');
var html = htmltable.outerHTML;
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
</script>
This script works fine in Mozilla Firefox,it pops-up with a dialog box of excel and ask for open or save options. But when I tested same script in Chrome browser it is not working as expected,when clicked on button there is no pop-up for excel. Data gets downloaded in a file with "file type : file" , no extension like .xls
There are no errors in chrome console.
Jsfiddle example :
http://jsfiddle.net/insin/cmewv/
This works fine in mozilla but not in chrome.
Chrome browser Test Case :
First Image:I click on Export to excel button
and result :
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:
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
Datatable plugin solves the purpose best and allows us to export the HTML table data into Excel , PDF , TEXT. easily configurable.
Please find the complete example in below datatable reference link :
https://datatables.net/extensions/buttons/examples/html5/simple.html
(screenshot from datatable reference site)
This could help
function exportToExcel(){
var htmls = "";
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
};
htmls = "YOUR HTML AS TABLE"
var ctx = {
worksheet : 'Worksheet',
table : htmls
}
var link = document.createElement("a");
link.download = "export.xls";
link.href = uri + base64(format(template, ctx));
link.click();
}
You can use tableToExcel.js to export table in excel file.
This works in a following way :
1). Include this CDN in your project/file
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel#v1.0.4/dist/tableToExcel.js"></script>
2). Either Using JavaScript:
<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>
function exportReportToExcel() {
let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xlsx`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
}
3). Or by Using Jquery
<button id="btnExport">EXPORT REPORT</button>
$(document).ready(function(){
$("#btnExport").click(function() {
let table = document.getElementsByTagName("table");
TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
name: `export.xlsx`, // fileName you could use any name
sheet: {
name: 'Sheet 1' // sheetName
}
});
});
});
You may refer to this github link for any other information
https://github.com/linways/table-to-excel/tree/master
or for referring the live example visit the following link
https://codepen.io/rohithb/pen/YdjVbb
Hope this will help someone :-)
Instead of using window.open you can use a link with the onclick event.
And you can put the html table into the uri and set the file name to be downloaded.
Live demo :
function exportF(elem) {
var table = document.getElementById("table");
var html = table.outerHTML;
var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url
elem.setAttribute("href", url);
elem.setAttribute("download", "export.xls"); // Choose the file name
return false;
}
<table id="table" border="1">
<tr>
<td>
Foo
</td>
<td>
Bar
</td>
</tr>
</table>
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>
TableExport - The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.
To use this library, simple call the TableExport constructor:
new TableExport(document.getElementsByTagName("table"));
// OR simply
TableExport(document.getElementsByTagName("table"));
// OR using jQuery
$("table").tableExport();
Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data. See here more info
http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/
try this link it might solve your problem
My merge of these examples:
https://www.codexworld.com/export-html-table-data-to-excel-using-javascript
https://bl.ocks.org/Flyer53/1de5a78de9c89850999c
function exportTableToExcel(tableId, filename) {
let dataType = 'application/vnd.ms-excel';
let extension = '.xls';
let base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
let template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
let render = function(template, content) {
return template.replace(/{(\w+)}/g, function(m, p) { return content[p]; });
};
let tableElement = document.getElementById(tableId);
let tableExcel = render(template, {
worksheet: filename,
table: tableElement.innerHTML
});
filename = filename + extension;
if (navigator.msSaveOrOpenBlob)
{
let blob = new Blob(
[ '\ufeff', tableExcel ],
{ type: dataType }
);
navigator.msSaveOrOpenBlob(blob, filename);
} else {
let downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.href = 'data:' + dataType + ';base64,' + base64(tableExcel);
downloadLink.download = filename;
downloadLink.click();
}
}
Simplest way using Jquery
Just add this:
<script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel#v1.0.4/dist/tableToExcel.js"></script>
Then add Jquery script:
<script type="text/javascript">
$(document).ready(function () {
$("#exportBtn1").click(function(){
TableToExcel.convert(document.getElementById("tab1"), {
name: "Traceability.xlsx",
sheet: {
name: "Sheet1"
}
});
});
});
</script>
Then add HTML button:
<button id="exportBtn1">Export To Excel</button><br><br>
Note: "exportBtn1" will be button ID and
"tab1" will be table ID
You can use a library like ShieldUI to do that.
It supports exporting to both XML and XLSX widely-used Excel formats.
More details here: http://demos.shieldui.com/web/grid-general/export-to-excel
Regarding to sampopes answer from Jun 6 '14 at 11:59:
I have insert a css style with font-size of 20px to display the excel data greater. In sampopes code the leading <tr> tags are missing, so i first output the headline and than the other tables lines within a loop.
function fnExcelReport()
{
var tab_text = '<table border="1px" style="font-size:20px" ">';
var textRange;
var j = 0;
var tab = document.getElementById('DataTableId'); // id of table
var lines = tab.rows.length;
// the first headline of the table
if (lines > 0) {
tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
}
// table data lines, loop starting from 1
for (j = 1 ; j < lines; j++) {
tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</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
// console.log(tab_text); // aktivate so see the result (press F12 in browser)
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
// if Internet Explorer
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
}
else // other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
function exportToExcel() {
var tab_text = "<tr bgcolor='#87AFC6'>";
var textRange; var j = 0, rows = '';
tab = document.getElementById('student-detail');
tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";
var tableData = $('#student-detail').DataTable().rows().data();
for (var i = 0; i < tableData.length; i++) {
rows += '<tr>'
+ '<td>' + tableData[i].value1 + '</td>'
+ '<td>' + tableData[i].value2 + '</td>'
+ '<td>' + tableData[i].value3 + '</td>'
+ '<td>' + tableData[i].value4 + '</td>'
+ '<td>' + tableData[i].value5 + '</td>'
+ '<td>' + tableData[i].value6 + '</td>'
+ '<td>' + tableData[i].value7 + '</td>'
+ '<td>' + tableData[i].value8 + '</td>'
+ '<td>' + tableData[i].value9 + '</td>'
+ '<td>' + tableData[i].value10 + '</td>'
+ '</tr>';
}
tab_text += rows;
var data_type = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',
base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
}
var ctx = {
worksheet: "Sheet 1" || 'Worksheet',
table: tab_text
}
document.getElementById("dlink").href = data_type + base64(format(template, ctx));
document.getElementById("dlink").download = "StudentDetails.xls";
document.getElementById("dlink").traget = "_blank";
document.getElementById("dlink").click();
}
Here Value 1 to 10 are column names that you are getting
Below code will work on latest Chrome , Edge , Firefox , not require 3rd party library.
HTML
<button onclick="download_table_as_csv('MyTableID_Value');">Export as CSV</button>
Jscript
function download_table_as_csv(table_id, separator = ',') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
My version of #sampopes answer
function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) {
if (that == null || typeof that === 'undefined') {
console.log('Sender is required');
return false;
}
if (!(that instanceof HTMLAnchorElement)) {
console.log('Sender must be an anchor element');
return false;
}
if (id == null || typeof id === 'undefined') {
console.log('Table id is required');
return false;
}
if (hasHeader == null || typeof hasHeader === 'undefined') {
hasHeader = true;
}
if (removeLinks == null || typeof removeLinks === 'undefined') {
removeLinks = true;
}
if (removeImages == null || typeof removeImages === 'undefined') {
removeImages = false;
}
if (removeInputParams == null || typeof removeInputParams === 'undefined') {
removeInputParams = true;
}
var tab_text = "<table border='2px'>";
var textRange;
tab = $(id).get(0);
if (tab == null || typeof tab === 'undefined') {
console.log('Table not found');
return;
}
var j = 0;
if (hasHeader && tab.rows.length > 0) {
var row = tab.rows[0];
tab_text += "<tr bgcolor='#87AFC6'>";
for (var l = 0; l < row.cells.length; l++) {
if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only
tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
}
}
tab_text += "</tr>";
j++;
}
for (; j < tab.rows.length; j++) {
var row = tab.rows[j];
tab_text += "<tr>";
for (var l = 0; l < row.cells.length; l++) {
if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only
tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
}
}
tab_text += "</tr>";
}
tab_text = tab_text + "</table>";
if (removeLinks)
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");
if (removeImages)
tab_text = tab_text.replace(/<img[^>]*>/gi, "");
if (removeInputParams)
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
myIframe.document.open("txt/html", "replace");
myIframe.document.write(tab_text);
myIframe.document.close();
myIframe.focus();
sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls");
return true;
}
else {
//other browser tested on IE 11
var result = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);
that.href = result;
that.download = document.title + ".xls";
return true;
}
}
Requires an iframe
<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>
Usage
$("#btnExportToExcel").click(function () {
exportToExcel(this, '#mytable');
});
Very Easy Code
Follow this instruction
Create excel.php file in your localhost root directory and copy and past this code.
Like this
http://localhost/excel.php?fileName=excelfile&link=1
<!-- http://localhost/excel.php?fileName=excelfile&link=2 -->
<!DOCTYPE html>
<html>
<head>
<title>Export excel file from html table</title>
</head>
<body style="display:
<?php
if( $_REQUEST['link'] == 1 ){
echo 'none';
}
?>;
">
<!-- --------Optional-------- -->
Excel <input type="radio" value="1" name="exportFile">
Others <input type="radio" value="2" name="exportFile">
<button onclick="myFunction()">Download</button>
<br>
<br>
<!-- --------/Optional-------- -->
<table width="100%" id="tblData">
<tbody>
<tr>
<th>Student Name</th>
<th>Group</th>
<th>Roll No.</th>
<th>Class</th>
<th>Contact No</th>
</tr>
<tr>
<td>Bulbul Sarker</td>
<td>Science</td>
<td>1</td>
<td>Nine</td>
<td>01724....</td>
</tr>
<tr>
<td>Karim</td>
<td>Science</td>
<td>3</td>
<td>Nine</td>
<td>0172444...</td>
</tr>
</tbody>
</table>
</body>
</html>
<style>
table#tblData{
border-collapse: collapse;
}
#tblData th,
#tblData td{
border:1px solid #CCC;
text-align: center;
}
</style>
<script type="text/javascript">
/*--------Optional--------*/
function myFunction() {
let val = document.querySelector('input[name="exportFile"]:checked').value;
if(val == 1)
{
this.exportTableToExcel();
}
}
/*--------/Optional--------*/
function exportTableToExcel(){
let filename2 = "<?php echo $_REQUEST['fileName']; ?>";
let tableId = 'tblData';
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableId);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
let filename = filename2?filename2+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
<?php
if( $_REQUEST['link'] == 1 ){
echo '<script type="text/javascript">
exportTableToExcel();
</script>';
}
?>
Html
<a onclick="download_to_excel()">Download</a>
<table id="tableId">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">Data Not Found</td>
</tr>
</tbody>
</table>
JavaScript
function download_to_excel()
{
var tab_text="<table><tr>";
var textRange = '';
var j=0;
var tab = document.getElementById('tableId'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text += tab.rows[j].innerHTML+"</tr>";
}
tab_text +="</table>";
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + ', ' + encodeURIComponent(tab_text);
//setting the file name
a.download = 'file_name.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
}