将数据从 html table 导出到 csv 文件时如何删除列?
How to drop a column when exporting data from html table to csv file?
假设,我有一个 table 如下所示:
我需要删除“联系人”列并将剩余的列导出到 CSV 文件。
HTML:
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
点击下载按钮,会调用js函数。
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
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);
}
错误:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
如何通过排除特定列将 table 数据导出到 CSV?有什么方法可以实现。
谢谢。
如果您找到 table headers 的 collection 并从中找到在其 textContent 中包含排除项 ( Contact
) 的单元格,您可以使用它稍后索引以排除同一索引的 table 个单元格(每行)。
<!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>
假设,我有一个 table 如下所示:
我需要删除“联系人”列并将剩余的列导出到 CSV 文件。
HTML:
<button id="downl" onclick="dropColumn('mytableid');">Download</button>
点击下载按钮,会调用js函数。
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
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);
}
错误:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'table#[object Object]tr' is not a valid selector.
如何通过排除特定列将 table 数据导出到 CSV?有什么方法可以实现。
谢谢。
如果您找到 table headers 的 collection 并从中找到在其 textContent 中包含排除项 ( Contact
) 的单元格,您可以使用它稍后索引以排除同一索引的 table 个单元格(每行)。
<!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>