-
-
Save luislobo14rap/b4d418a7834b625efae8fbcd24611729 to your computer and use it in GitHub Desktop.
tableToCSV.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tableToCSV.js v1 | |
// how use: tableToCSV( document.querySelector('table'), getInvisibleValues ) // getInvisibleValues is 0 OR 1 | |
// salvarComo.js v1 | |
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ | |
var saveAs=saveAs||function(e){"use strict";if(typeof e==="undefined"||typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var t=e.document,n=function(){return e.URL||e.webkitURL||e},r=t.createElementNS("http://www.w3.org/1999/xhtml","a"),o="download"in r,a=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},i=/constructor/i.test(e.HTMLElement)||e.safari,f=/CriOS\/[\d]+/.test(navigator.userAgent),u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",d=1e3*40,c=function(e){var t=function(){if(typeof e==="string"){n().revokeObjectURL(e)}else{e.remove()}};setTimeout(t,d)},l=function(e,t,n){t=[].concat(t);var r=t.length;while(r--){var o=e["on"+t[r]];if(typeof o==="function"){try{o.call(e,n||e)}catch(a){u(a)}}}},p=function(e){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)){return new Blob([String.fromCharCode(65279),e],{type:e.type})}return e},v=function(t,u,d){if(!d){t=p(t)}var v=this,w=t.type,m=w===s,y,h=function(){l(v,"writestart progress write writeend".split(" "))},S=function(){if((f||m&&i)&&e.FileReader){var r=new FileReader;r.onloadend=function(){var t=f?r.result:r.result.replace(/^data:[^;]*;/,"data:attachment/file;");var n=e.open(t,"_blank");if(!n)e.location.href=t;t=undefined;v.readyState=v.DONE;h()};r.readAsDataURL(t);v.readyState=v.INIT;return}if(!y){y=n().createObjectURL(t)}if(m){e.location.href=y}else{var o=e.open(y,"_blank");if(!o){e.location.href=y}}v.readyState=v.DONE;h();c(y)};v.readyState=v.INIT;if(o){y=n().createObjectURL(t);setTimeout(function(){r.href=y;r.download=u;a(r);h();c(y);v.readyState=v.DONE});return}S()},w=v.prototype,m=function(e,t,n){return new v(e,t||e.name||"download",n)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(e,t,n){t=t||e.name||"download";if(!n){e=p(e)}return navigator.msSaveOrOpenBlob(e,t)}}w.abort=function(){};w.readyState=w.INIT=0;w.WRITING=1;w.DONE=2;w.error=w.onwritestart=w.onprogress=w.onwrite=w.onabort=w.onerror=w.onwriteend=null;return m}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!==null){define("FileSaver.js",function(){return saveAs})} | |
//permite salvar arquivos de textos (como TXT e CSV) com facilidade. Para funcionar é necessário o uso do fileSaver acima | |
top.salvarComo = function(fileName, fileExtension, fileContent){ | |
let lines = ''; | |
let cells = ''; | |
//fileExtension | |
fileExtension = fileExtension.toLowerCase(); | |
if( fileExtension[0] != '.' ){ | |
fileExtension = '.' + fileExtension; | |
}; | |
//console.log(fileExtension); | |
//fileName (valid filename for Windows OS) | |
fileName = fileName.replace(/[\\/:*?"<>|]/g, '_').replace(/\s{1,}/g, ' ').trim(); | |
//console.log(fileName); | |
//toCSV | |
if(fileExtension == '.csv'){ | |
//create lines | |
let lines = fileContent.split('\n'); | |
for(let i = 0; i < lines.length; i++){ | |
//create cells | |
cells = lines[i].split(' '); | |
for(j = 0; j < cells.length; j++){ | |
//normalize CSV if contains '"' or ';' | |
if( cells[j].indexOf('"') > -1 || cells[j].indexOf(';') > -1 ){ | |
cells[j] = '"' + cells[j].replace(/"/g, '""') + '"'; | |
}; | |
cells[j] += ';'; | |
}; | |
cells.push('\n'); | |
lines[i] = cells.join(''); | |
}; | |
//total | |
fileContent = lines.join(''); | |
}; | |
//salvarComo using SaveAs (fileSaver) | |
let blob = new Blob([fileContent], {type : 'text/plain;charset=utf-8'}); | |
saveAs(blob, fileName + fileExtension); | |
}; | |
// tableToCSV.js v1 | |
function tableToCSV(table, getInvisible = 0){ | |
if(typeof table.tagName === 'string'){ | |
let csv = [], | |
table_trs = table.querySelectorAll('tr'); | |
if(ifExist(table_trs)){ | |
for(let i = 0; i < table_trs.length; i++){ | |
let this_tr = table_trs[i], | |
table_tds = this_tr.querySelectorAll('th, td'); | |
if(ifExist(table_tds)){ | |
let thisLine = []; | |
for(let i = 0; i < table_tds.length; i++){ | |
let thisCell = table_tds[i], | |
thisParent = thisCell.parentElement, | |
isVisible = true; | |
if(getInvisible === 0){ | |
while(thisParent !== table){ | |
if(getComputedStyle(thisCell, null).display === 'none' || thisCell.offsetHeight <= 3){ | |
isVisible = false; | |
thisParent = table.children[0]; | |
}; | |
thisParent = thisParent.parentElement; | |
}; | |
}; | |
if(isVisible){ | |
thisLine.push(thisCell.innerText.replace(/[\s\uFEFF\xA0]+/g, ' ').replace(/(^ +| +$)/g, '')); | |
}; | |
}; | |
if(ifExist(thisLine)){ | |
csv.push(thisLine.join(' ')); | |
}; | |
}; | |
}; | |
}; | |
csv = csv.join('\n'); | |
// console.log(csv); | |
salvarComo('tableToCSV_' + getTimeInString('year-month-day hours-minutes-seconds'), 'csv', csv); | |
}; | |
function ifExist(element){ | |
if(element !== null){ | |
if((element.length === undefined && typeof element.tagName === 'string') || element.length > 0){ | |
return true; | |
}; | |
}; | |
return false; | |
}; | |
function getTimeInString(text){ | |
let newDate = new Date() | |
, _fullYear = newDate.getFullYear() | |
, _month = newDate.getMonth() | |
, _date = newDate.getDate() | |
, _hours = newDate.getHours() | |
, _minutes = newDate.getMinutes() | |
, _seconds = newDate.getSeconds(); | |
_month = ( _month > 9 ? _month : '0' + _month.toString() ) | |
_date = ( _date > 9 ? _date : '0' + _date.toString() ) | |
_hours = ( _hours > 9 ? _hours : '0' + _hours.toString() ) | |
_minutes = ( _minutes > 9 ? _minutes : '0' + _minutes.toString() ) | |
_seconds = ( _seconds > 9 ? _seconds : '0' + _seconds.toString() ) | |
text = text | |
.replace(/year/g, _fullYear ) | |
.replace(/month/g, _month ) | |
.replace(/day/g, _date ) | |
.replace(/hours/g, _hours ) | |
.replace(/minutes/g, _minutes ) | |
.replace(/seconds/g, _seconds ); | |
return text; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tableToCSV(tableSelector, 0 OR 1)