Skip to content

Instantly share code, notes, and snippets.

@rascoop
Last active January 17, 2021 01:34
Show Gist options
  • Save rascoop/8944030 to your computer and use it in GitHub Desktop.
Save rascoop/8944030 to your computer and use it in GitHub Desktop.
function csvQuoteCell(cell, quotechar, sepchar) {
// quote cells containing sepchar and double quote chars
// this is an excel dialect
var quoted = cell;
if (cell.indexOf(sepchar)!==-1) {
if (cell.indexOf(quotechar)!==-1) {
quoted = quoted.replace(quotechar, quotechar+quotechar);
}
quoted = quotechar+quoted+quotechar;
}
return quoted;
}
function array2csv(ar, quotechar, sepchar) {
var quoted = [];
for (var i=0;i<ar.length;i++) {
quoted.push(csvQuoteCell(ar[i], quotechar, sepchar));
}
return quoted.join(sepchar);
}
var db = openDatabase('mydb','1.0','thedatabase',1024*1024);
db.readTransaction(function(tx){
tx.executeSql('SELECT col1, col2, col3 FROM thetable', [], function(tx, results){
var quotechar = '"';
var sepchar = ',';
var row, rowarray, csvstring;
var csvs = [];
var fieldnames = ['col1','col2','col3'];
// this is the header row
csvs.append(array2csv(fieldnames, quotechar, sepchar));
for (var i=0; i<results.rows.length; i++) {
row = results.rows.item(i);
// you need to make sure you have an explicit order for the csv
// row is an object with unordered keys!
rowarray = [];
for (var j=0;j<fieldnames.length;j++) {
rowarray.push(row[fieldnames[j]]);
}
csvs.push(array2csv(rowarray, quotechar, sepchar));
}
csvstring = csvs.join('\r\n');
// csvstring should now contain a multirow csv string
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment