问题
I am writing an app that will run in an webkit browser. I need it to take the data locally stored on the device and export it in a .csv format. Is this possible using javascript? It would have to be done in browser. Php isnt an option. Thanks
回答1:
You can do this, but you will need to serialize your javascript to csv by hand. You will also need to decide what CSV dialect to use.
Below is one (untested) possibility that shows the general pattern you must use.
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
});
});
However, it's probably not possible to "download" that file from javascript to the local filesystem, only to upload it to a server. Depending on your exact browser environment, you may be able to use the very-draft FileWriter api, some kind of flash or java applet shim, or maybe some proprietary API offered by your device.
回答2:
Assuming that the sqlite file is located on the server (we're not talking about local storage, right?), you'll still need to access the file server-side.
来源:https://stackoverflow.com/questions/9182743/how-to-export-web-sql-to-a-csv-file