使用 vanilla javascript 将 HTML 表导出为 CSV [英] Export HTML table to CSV using vanilla javascript
问题描述
我正在尝试在我的网站中添加 csv 下载选项的功能.它应该将网站中存在的 html 表转换为 csv 内容并使其可下载.我一直在网上搜索一个好的插件,发现了一些有用的插件,比如 http://www.dev-skills.com/export-html-table-to-csv-file/ 但它使用php脚本来做下载部分.我想知道是否有一个纯 javascript 库可用于使用 node.js 等服务器端软件而不使用 php??
I am trying to add a feature of csv download option in my website. It should convert the html table present in the website in to csv content and make it downloadable. Ive been searching through internet for a good plugin and found some usefule ones like http://www.dev-skills.com/export-html-table-to-csv-file/ But it uses php script to do the download part. I was wondering if there is a pure javascript library available to do this feature using server side softwares like node.js without the use of php??
推荐答案
应该适用于所有现代浏览器,并且没有 jQuery 或任何依赖,这里是我的实现:
Should work on every modern browser and without jQuery or any dependency, here my implementation :
// 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(/(
|
|
)/gm, '').replace(/(ss)/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('
');
// 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);
}
然后添加您的下载按钮/链接:
Then add your download button/link :
<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>
CSV 文件有时间限制并与默认 Excel 格式兼容.
CSV file is timedated and compatible with default Excel format.
评论后更新:添加了第二个参数separator",它可以用来配置另一个字符,如;
,如果你有用户下载你的csv,这很有用世界不同地区,因为他们可以为 Excel 使用另一个默认分隔符,有关详细信息,请参阅:https://superuser.com/a/606274/908273
Update after comments: Added second parameter "separator", it can be used to configure another character like ;
, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273
这篇关于使用 vanilla javascript 将 HTML 表导出为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!