Assume, Im having a table like below:
I need to drop the “Contact” column and export the remaining column to the CSV file.
HTML:
JavaScript
x
2
1
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
2
On click of the download button, js function will get called.
JavaScript
JavaScript
1
38
38
1
//Drop Column
2
function dropColumn(mytableid){
3
var clonetable = $('#mytableid').clone();
4
clonetable.find('td:nth-child(2),(the:nth-child(2)').remove();
5
download_table_as_csv(clonetable);
6
}
7
8
//Download as CSV
9
function download_table_as_csv(table_id, separator = ',') {
10
// Select rows from table_id
11
var rows = document.querySelectorAll('table#' + table_id + ' tr');
12
// Construct csv
13
var csv = [];
14
for (var i = 0; i < rows.length; i++) {
15
var row = [], cols = rows[i].querySelectorAll('td, th');
16
for (var j = 0; j < cols.length; j++) {
17
// Clean innertext to remove multiple spaces and jumpline (break csv)
18
var data = cols[j].innerText.replace(/(rn|n|r)/gm, '').replace(/(ss)/gm, ' ')
19
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
20
data = data.replace(/"/g, '""');
21
// Push escaped string
22
row.push('"' + data + '"');
23
}
24
csv.push(row.join(separator));
25
}
26
var csv_string = csv.join('n');
27
// Download it
28
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
29
var link = document.createElement('a');
30
link.style.display = 'none';
31
link.setAttribute('target', '_blank');
32
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
33
link.setAttribute('download', filename);
34
document.body.appendChild(link);
35
link.click();
36
document.body.removeChild(link);
37
}
38
Error:
JavaScript
1
2
1
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
2
How to export table data to CSV by excluding a specific column?.Any way to achieve this.
Thanks.
Advertisement
Answer
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.
JavaScript
1
96
96
1
<!DOCTYPE html>
2
<html lang='en'>
3
<head>
4
<meta charset='utf-8' />
5
<title>Export HTML table - exclude column by text content or other criteria</title>
6
<script>
7
document.addEventListener('DOMContentLoaded',()=>{
8
9
const preparetext=function(text,regex,rep){
10
text=text.replace(/(rn|n|r)/gm, '');
11
text=text.replace(/(ss)/gm, ' ');
12
text=text.replace(/"/g, '""');
13
return text;
14
};
15
16
document.querySelector('input[type="button"][name="export"]').addEventListener('click',e=>{
17
let table=document.querySelector('table#geronimo');
18
let colHeaders=table.querySelectorAll('tr th');
19
let colRows=table.querySelectorAll('tr:not( .headers )');
20
21
let index=-1;
22
let exclude='Contact';
23
let headers=[];
24
let data=[];
25
26
colHeaders.forEach( ( th, i )=>{
27
if( th.textContent!=exclude )headers.push( [ '"', preparetext( th.textContent ), '"' ].join('') )
28
else index=i;
29
});
30
31
data.push( headers.join(',') );
32
data.push( String.fromCharCode(10) );
33
34
35
36
if( index > -1 ){
37
colRows.forEach( tr => {
38
39
let cells=tr.querySelectorAll('td');
40
let row=[];
41
42
cells.forEach( ( td, i )=>{
43
if( i !== index ) row.push( [ '"', preparetext( td.textContent), '"' ].join('') )
44
});
45
46
data.push( row.join(',') );
47
data.push( String.fromCharCode(10) );
48
});
49
50
let a=document.createElement('a');
51
a.download='export_'+table.id+'_'+( new Date().toLocaleDateString() )+'.csv';
52
a.href=URL.createObjectURL( new Blob( data ) );
53
a.click();
54
}
55
})
56
});
57
</script>
58
</head>
59
<body>
60
<table id='geronimo'>
61
<tr class='headers'>
62
<th scope='col'>Company</th>
63
<th scope='col'>Contact</th>
64
<th scope='col'>Country</th>
65
</tr>
66
<tr>
67
<td>Jolly Roger Cookery School Ltd</td>
68
<td>Blackbeard</td>
69
<td>Jamaica</td>
70
</tr>
71
<tr>
72
<td>Autonomous Hedgehog Collective</td>
73
<td>Mr. Ben</td>
74
<td>United Kingdom</td>
75
</tr>
76
<tr>
77
<td>The Cock Inn</td>
78
<td>Miss. Tilly Lykes</td>
79
<td>Scotland</td>
80
</tr>
81
<tr>
82
<td>Hooker Furniture</td>
83
<td>Hubert</td>
84
<td>Hanoi</td>
85
</tr>
86
<tr>
87
<td>Horrible Haggis Hunt</td>
88
<td>Horace Hubert</td>
89
<td>Hungary</td>
90
</tr>
91
92
</table>
93
<input type='button' name='export' value='Download CSV' />
94
</body>
95
</html>
96