Last active
January 17, 2021 01:34
-
-
Save rascoop/8944030 to your computer and use it in GitHub Desktop.
How to Export Web SQL to a .CSV File - http://stackoverflow.com/questions/9182743/how-to-export-web-sql-to-a-csv-file
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
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