Skip to content

Instantly share code, notes, and snippets.

@neodigm
Last active August 4, 2022 20:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neodigm/d854493b519a94c6410089eacfe3fdf5 to your computer and use it in GitHub Desktop.
Save neodigm/d854493b519a94c6410089eacfe3fdf5 to your computer and use it in GitHub Desktop.
// 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()
);
*/
@neodigm
Copy link
Author

neodigm commented Feb 27, 2021

  1. The resulting CSV files will contain a header row with deterministic column names.
  2. The resulting CSV files will be quoted. Meaning each cell will be surrounded by double quotes.
  3. Cell string data may contain a comma “,” however quotes will be removed.
  4. 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