Javascript 将html表格导出到csv
我正在尝试在我的网站中添加csv下载选项的功能。它应该将网站中的html表格转换为csv内容,并使其可下载。我一直在互联网上搜索一个好的插件,找到了一些有用的插件,比如,但它使用php脚本来完成下载部分。我想知道是否有一个纯javascript库可以使用服务器端软件(如node.js)来实现此功能,而不使用php???只使用Javascript 将html表格导出到csv,javascript,jquery,node.js,html-table,export-to-csv,Javascript,Jquery,Node.js,Html Table,Export To Csv,我正在尝试在我的网站中添加csv下载选项的功能。它应该将网站中的html表格转换为csv内容,并使其可下载。我一直在互联网上搜索一个好的插件,找到了一些有用的插件,比如,但它使用php脚本来完成下载部分。我想知道是否有一个纯javascript库可以使用服务器端软件(如node.js)来实现此功能,而不使用php???只使用jQuery、vanillajavascript和table2CSV库: 将此代码放入要加载到标题中的脚本中部分: $(document).ready(function
jQuery
、vanillajavascript
和table2CSV
库:
将此代码放入要加载到标题中的脚本中
部分:
$(document).ready(function () {
$('table').each(function () {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to spreadsheet");
$button.insertAfter($table);
$button.click(function () {
var csv = $table.table2CSV({
delivery: 'value'
});
window.location.href = 'data:text/csv;charset=UTF-8,'
+ encodeURIComponent(csv);
});
});
})
$(文档).ready(函数(){
$('table')。每个(函数(){
var$表=$(此);
var$按钮=$(“”);
$button.text(“导出到电子表格”);
$button.insertAfter($table);
$按钮。单击(函数(){
var csv=$table.table2CSV({
交付:“价值”
});
window.location.href='data:text/csv;charset=UTF-8,'
+编码组件(csv);
});
});
})
注:
需要和:在上述脚本之前向两个库添加脚本引用
表
选择器用作示例,可以根据您的需要进行调整
它只适用于完全支持数据URI
的浏览器:Firefox、Chrome和Opera,而不适用于IE,IE只支持数据URI
将二进制图像数据嵌入页面
要实现完全的浏览器兼容性,您必须使用稍微不同的方法,即需要服务器端脚本来
echo
CSV。您不需要服务器端的PHP脚本。仅在客户端,在接受以下内容的浏览器中执行此操作:
数据URI类似于:
data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333
您可以通过以下方式调用此URI:
- 使用
窗口。打开
- 或设置
窗口。位置
- 或者通过一个锚
- 通过添加下载属性,它将在chrome中工作,但仍需在IE中测试
<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>
现在有一个非常简单的免费开源解决方案 首先从下载javascript文件和示例文件 html页面如下所示 确保javascript文件位于同一文件夹中,或者相应地更改html文件中脚本的路径
<html>
<head>
<title>Export to excel test</title>
<script src="excellentexport.js"></script>
<style>
table, tr, td {
border: 1px black solid;
}
</style>
</head>
<body>
<h1>ExcellentExport.js</h1>
Check on <a href="http://jordiburgos.com">jordiburgos.com</a> and <a href="https://github.com/jmaister/excellentexport">GitHub</a>.
<h3>Test page</h3>
<br/>
<a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
<br/>
<a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>
<br/>
<table id="datatable">
<tr>
<th>Column 1</th>
<th>Column "cool" 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>100,111</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
<tr>
<td>Text</td>
<td>More text</td>
<td>Text with
new line</td>
</tr>
</table>
</body>
导出到excel测试
表,tr,td{
边框:1px黑色实心;
}
ExcellentExport.js
检查并确认。
测试页
第1栏
“酷”列2
第3栏
100,111
200
300
400
500
600
正文
更多文本
文本与
新线
这很容易使用,因为我已经尝试了大多数其他方法。我发现有一个用于此的库。请参见此处的示例: 除上述代码外,还加载了以下Javascript库文件以供本例使用: 在HTML中,包括以下脚本:
jquery.dataTables.min.js
dataTables.editor.min.js
dataTables.select.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js
buttons.print.min.js
通过添加以下脚本来启用按钮:
<script>
$(document).ready( function () {
$('#table-arrays').DataTable({
dom: '<"top"Blf>rt<"bottom"ip>',
buttons: ['copy', 'excel', 'csv', 'pdf', 'print'],
select: true,
});
} );
</script>
$(文档).ready(函数(){
$('#表数组')。数据表({
dom:'rt',
按钮:[“复制”、“excel”、“csv”、“pdf”、“打印”],
选择:true,
});
} );
由于某些原因,excel导出会导致文件损坏,但可以修复。或者,禁用excel并使用csv导出。使用了上述答案,但根据我的需要对其进行了更改 我使用了以下功能并导入到我的REACT文件中,在那里我需要下载csv文件 我在
th
元素中有一个span
标记。对大多数函数/方法的功能添加了注释
import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';
export function tableToCSV(){
let tableHeaders = Array.from(document.querySelectorAll('th'))
.map(item => {
// title = splits elem tags on '\n',
// then filter out blank "" that appears in array.
// ex ["Timestamp", "[Full time]", ""]
let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
return title
}).join(",")
const rows = Array.from(document.querySelectorAll('tr'))
.reduce((arr, currRow) => {
// if tr tag contains th tag.
// if null return array.
if (currRow.querySelector('th')) return arr
// concats individual cells into csv format row.
const cells = Array.from(currRow.querySelectorAll('td'))
.map(item => item.innerText)
.join(',')
return arr.concat([cells])
}, [])
return tableHeaders + '\n' + rows.join('\n')
}
export function downloadCSV(csv){
const csvFile = new Blob([csv], { type: 'text/csv' })
const downloadLink = document.createElement('a')
// sets the name for the download file
downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
// sets the url to the window URL created from csv file above
downloadLink.href = window.URL.createObjectURL(csvFile)
// creates link, but does not display it.
downloadLink.style.display = 'none'
// add link to body so click function below works
document.body.appendChild(downloadLink)
downloadLink.click()
}
当用户单击“导出到csv”时,将触发react中的以下功能
handleExport = (e) => {
e.preventDefault();
const csv = tableToCSV()
return downloadCSV(csv)
}
示例html表格元素
<table id="datatable">
<tbody>
<tr id="tableHeader" className="t-header">
<th>Timestamp
<span className="block">full time</span></th>
<th>current rate
<span className="block">alt view</span>
</th>
<th>Battery Voltage
<span className="block">current voltage
</span>
</th>
<th>Temperature 1
<span className="block">[C]</span>
</th>
<th>Temperature 2
<span className="block">[C]</span>
</th>
<th>Time & Date </th>
</tr>
</tbody>
<tbody>
{this.renderData()}
</tbody>
</table>
</div>
时间戳
全场比赛结束时间
现行汇率
alt视图
电池电压
电流电压
温度1
[丙]
温度2
[丙]
时间和日期
{this.renderData()}
应适用于所有现代浏览器,且无需jQuery或任何依赖项,以下是我的实现:
// Quick and simple export target #table_id into a 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);
}
//快速简单地将目标#表_id导出到csv
函数下载为csv的表格(表格id,分隔符=','){
//从表\u id中选择行
var rows=document.querySelectorAll('table#'+table_id+'tr');
//构建csv
var csv=[];
对于(变量i=0;i <table id="datatable">
<tbody>
<tr id="tableHeader" className="t-header">
<th>Timestamp
<span className="block">full time</span></th>
<th>current rate
<span className="block">alt view</span>
</th>
<th>Battery Voltage
<span className="block">current voltage
</span>
</th>
<th>Temperature 1
<span className="block">[C]</span>
</th>
<th>Temperature 2
<span className="block">[C]</span>
</th>
<th>Time & Date </th>
</tr>
</tbody>
<tbody>
{this.renderData()}
</tbody>
</table>
</div>
// Quick and simple export target #table_id into a 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);
}
<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>
csv.push(row.join(';'));
function downloadAsCSV(tableEle, separator = ','){
let csvRows = []
//only get direct children of the table in question (thead, tbody)
Array.from(tableEle.children).forEach(function(node){
//using scope to only get direct tr of node
node.querySelectorAll(':scope > tr').forEach(function(tr){
let csvLine = []
//again scope to only get direct children
tr.querySelectorAll(':scope > td').forEach(function(td){
//clone as to not remove anything from original
let copytd = td.cloneNode(true)
let data
if(copytd.dataset.val) data = copytd.dataset.val.replace(/(\r\n|\n|\r)/gm, '')
else {
Array.from(copytd.children).forEach(function(remove){
//remove nested elements before getting text
remove.parentNode.removeChild(remove)
})
data = copytd.textContent.replace(/(\r\n|\n|\r)/gm, '')
}
data = data.replace(/(\s\s)/gm, ' ').replace(/"/g, '""')
csvLine.push('"'+data+'"')
})
csvRows.push(csvLine.join(separator))
})
})
var a = document.createElement("a")
a.style = "display: none; visibility: hidden" //safari needs visibility hidden
a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvRows.join('\n'))
a.download = 'testfile.csv'
document.body.appendChild(a)
a.click()
a.remove()
}