Last active
August 4, 2022 20:53
-
-
Save neodigm/d854493b519a94c6410089eacfe3fdf5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Desc: Produce CSV with client-side JS. Contruct Blob and Download as CSV file | |
let nativeCSV = ( ( _d )=>{ | |
let oCnt, jnCSV, sCSV, blCSV, elCSV; // config, json, array, blob, and element | |
let retObj = { | |
"init": ( _oCnt )=>{ | |
oCnt = _oCnt; | |
if( oCnt.fileName.indexOf("####") !== -1) { | |
oCnt.fileName = oCnt.fileName.replace("####", Date.now() );} | |
jnCSV = sCSV = blCSV = elCSV = ""; | |
return retObj; | |
}, | |
"setArray": ( _jnCSV )=>{ // An array (rows) of arrays (cols) !jagged | |
jnCSV = _jnCSV; | |
if( oCnt.header ) jnCSV.unshift( oCnt.header ); | |
jnCSV.forEach(( aRow )=>{ | |
aRow.forEach(( sCol )=>{ | |
if( typeof sCol === "string"){ | |
sCSV += oCnt.delimQuote + sCol | |
.split( oCnt.delimQuote ).join(""); | |
sCSV += oCnt.delimQuote + oCnt.delimCol; | |
} | |
}); | |
sCSV = sCSV.slice(0, -1) + oCnt.delimLine; | |
}); | |
return retObj; | |
}, | |
"getBlob": ()=>{ | |
blCSV = new Blob([ sCSV ], { type: "text/csv;charset=utf-8;" }); | |
return retObj; | |
}, | |
"createLink": ()=>{ | |
elCSV = _d.createElement("a"); | |
elCSV.setAttribute("href", URL.createObjectURL( blCSV )); | |
elCSV.setAttribute("download", oCnt.fileName ); | |
elCSV.style.visibility = 'hidden'; | |
_d.body.appendChild( elCSV ); | |
return retObj; | |
}, | |
"clickLink": ()=>{ | |
elCSV.click(); | |
return retObj; | |
}, | |
"removeLink": ()=>{ | |
_d.body.removeChild( elCSV ); | |
return retObj; | |
} | |
}; | |
return retObj; | |
})( document ); | |
// Usage: | |
/* | |
console.log( nativeCSV.init({ | |
"delimCol": ",", | |
"delimQuote": '"', | |
"delimLine": "\n", | |
"fileName": "graph_nodes_####.csv", | |
"header": ["id","name", "FQDN"]}) | |
.setArray( currentGraph2Array(jCurrentGraph) ) | |
.getBlob() | |
.createLink() | |
.clickLink() | |
.removeLink() | |
); | |
*/ |
Author
neodigm
commented
Feb 27, 2021
- The resulting CSV files will contain a header row with deterministic column names.
- The resulting CSV files will be quoted. Meaning each cell will be surrounded by double quotes.
- Cell string data may contain a comma “,” however quotes will be removed.
- Cell string data may contain only utf-8 characters.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment