我正在尝试在chrome(.db文件)中创建本地数据库。我只是想创建一个按钮,允许用户只使用数据库中的数据迁移或创建Excel工作表。我想在javascript中这样做。
以下是我的尝试:
1)我知道只能在IE中工作的ActiveX对象。但是,浏览器不支持数据库操作。因此,ActiveX被排除在外。
2)我可以使用像chrome这样的浏览器,但是,我不确定我是否可以通过javascript轻松创建csv文件。我不想从HTML导出表。我想像ActiveX一样完全控制csv文件。
请提供任何提示?
答案 0 :(得分:0)
如果要导出IndexedDB中的任何特定表,请参考下面的代码(这是我将db数据导出到csv文件的示例)
var transactionsRecorder = {};
transactionsRecorder.webdb = {};
transactionsRecorder.webdb.db = null;
transactionsRecorder.webdb.open = function () {
var dbSize = 5 * 1024 * 1024; // 5MB
transactionsRecorder.webdb.db = openDatabase("TransactionsRecorder", "1.0", "Transactions Recorder", dbSize);
}
$(document).ready(function(){
init();
});
function init() {
transactionsRecorder.webdb.open();
transactionsRecorder.webdb.createTable();
}
//Create Table Function
transactionsRecorder.webdb.createTable = function() {
var db = transactionsRecorder.webdb.db;
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS accounts (accNo INTEGER PRIMARY KEY ASC, accType INTEGER, accAlias TEXT, accAddedOn DATETIME, custId INTEGER, roi DECIMAL, principal DECIMAL, interest DECIMAL, accStatusId INTEGER, lastUpdatedInt DATETIME, lastUpdatedCust DATETIME)", []);
});
//Hardcode Insert Queries End
}
$("#exportAccount").click(function(){
var db = transactionsRecorder.webdb.db;
db.readTransaction(function(tx){
tx.executeSql('SELECT accNo, accAlias, accAddedOn, custId, roi, principal, interest, lastUpdatedInt FROM accounts', [], function(tx, results){
var quotechar = '"';
var sepchar = ',';
var row, rowarray, csvstring;
var csvs = [];
var fieldnames = ['accNo','accAlias','accAddedOn', 'custId', 'roi', 'principal', 'interest', 'lastUpdatedInt'];
// this is the header row
csvs.push(fieldnames.join(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(rowarray.join(sepchar));
}
csvstring = csvs.join('\r\n');
var blob = new Blob([csvstring], {type: "text/plain;charset=utf-8"});
var csvDate = new Date();
var csvDateStr = csvDate.getDate() + "_" + (csvDate.getMonth() + 1) + "_" + csvDate.getFullYear() + "_" + csvDate.getTime() ;
saveAs(blob, "account_"+ csvDateStr +".csv");
// csvstring should now contain a multirow csv string;
});
});
});