Funkce pro automatické vygenerování CSV z HTML tabulky pomocí čístého javascriptu.
Pro generování timestampu přilepeného k názvu souboru používám funkci toDateTimeFormat_full
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){ text = text.replace(/"/g, '""'); return '"'+text+'"'; };
$(this).each(function(){
var table = $(this);
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
download_link.download = "export_do_csv " + toDateTimeFormat_full(new Date()) + ".txt";
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};
function toDateTimeFormat_full(date) {
var d = new Date(date),
year = '' + d.getFullYear();
month = '' + (d.getMonth() + 1);
day = '' + d.getDate();
hour = '' + d.getHours();
min = '' + d.getMinutes();
sec = '' + d.getSeconds();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hour.length < 2) hour = '0' + hour;
if (min.length < 2) min = '0' + min;
if (sec.length < 2) sec = '0' + sec;
return [year, month, day].join('-') + ' ' + [hour, min, sec].join(':');
}
srpen 2019