如何将Web SQL导出到.CSV文件 [英] How to Export Web SQL to a .CSV File

查看:316
本文介绍了如何将Web SQL导出到.CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个将在webkit浏览器中运行的应用程序。我需要它来获取本地存储在设备上的数据,并以.csv格式导出。这是可能使用javascript吗?它必须在浏览器中完成。 Php不是选项。感谢

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

推荐答案

你可以这样做,但是你需要手动序列化你的javascript到csv。您还需要决定要使用什么CSV方言。

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
    });
});

但是,可能无法将该文件从javascript下载到本地文件系统,将其上传到服务器。根据您确切的浏览器环境,您可以使用非常草案的 FileWriter api ,某种闪存或Java applet shim,或者您的设备提供的一些专有API。

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.

这篇关于如何将Web SQL导出到.CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆