我正在创建一个表,并使用sqflite示例在其中保存数据。我希望将保存的表导出为csv文件。请任何人帮助我做同样的事情。我还经历了csv.drt。 我已经将sqflite dbhelper的代码编写为文件,以保存数据文件,该代码已在下面的代码中显示,并且将我的代码附加到了将表中的数据显示为卡视图的地方。
dbhelper.dart
import 'dart:async';
import 'package:model/Manageinventory_class.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DBProvider {
static final DBProvider _instance = new DBProvider.internal();
factory DBProvider() => _instance;
DBProvider.internal();
final String tableNote = 'noteTable';
final String columnId = 'id';
final String columnItem = 'item';
final String columnQuantity = 'quantity';
final String columnCategory = 'category';
final String columnUnit = 'unit';
final String columnLocation = 'location';
static Database _db;
Future<Database> get db async {
if (_db == null) _db = await initDb();
return _db;
}
initDb() async {
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'notes.db');
// await deleteDatabase(path); // just for testing
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
void _onCreate(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $tableNote($columnId INTEGER PRIMARY KEY, $columnItem REAL, $columnQuantity REAL, $columnCategory TEXT, $columnUnit TEXT, $columnLocation TEXT)');
}
Future<int> saveNote(Inventory note) async {
var dbClient = await db;
return await dbClient.insert(tableNote, note.toMap());
}
Future<List<Inventory>> getAllNotes() async {
var dbClient = await db;
var result = await dbClient
.query(tableNote, columns: [columnId, columnItem, columnQuantity, columnCategory, columnUnit, columnLocation]);
return result.map((r) => Inventory.fromMap(r)).toList();
}
Future<int> getCount() async {
var dbClient = await db;
return Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM $tableNote'));
}
Future<Inventory> getNote(int id) async {
var dbClient = await db;
List<Map> result = await dbClient.query(tableNote,
columns: [columnId, columnItem, columnQuantity, columnCategory, columnUnit, columnLocation],
where: '$columnId = ?',
whereArgs: [id]);
if (result.length > 0) {
return new Inventory.fromMap(result.first);
}
return null;
}
Future<int> deleteNote(int id) async {
var dbClient = await db;
return await dbClient.delete(tableNote, where: '$columnId = ?', whereArgs: [id]);
}
Future<int> updateNote(Inventory note) async {
var dbClient = await db;
return await dbClient.update(tableNote, note.toMap(), where: "$columnId = ?", whereArgs: [note.id]);
}
Future close() async {
return _db.close();
}
}
Inventory.dart
import 'package:flutter/material.dart';
import 'package:database/dbhelper_manage_inventory.dart';
import 'package:model/Manageinventory_class.dart';
class ManageInventory extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return ManageInventoryState();
}
}
class ManageInventoryState extends State<ManageInventory> {
DBProvider _db = DBProvider();
List<Inventory> _items = new List();
int count = 0;
@override
void initState() {
super.initState();
_reloadItems();
}
void _reloadItems() async {
_items.clear();
var items = await _db.getAllNotes();
setState(() {
_items = items;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Inventories'),
),
body: getManageStoreView());
}
getManageStoreView() {
return _items.isEmpty
? Padding(
padding: EdgeInsets.all(10.0),
child: Center(
child: Text(
'No Stores created yet',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.normal),
)))
: ListView.builder(
itemCount: _items.length,
itemBuilder: (BuildContext context, int position) {
return Card(
elevation: 2.0,
child: Column(
children: <Widget>[
ListTile(
title: Text('Item name : ${_items[position].item}',
style: TextStyle(fontWeight: FontWeight.bold)),
),
ListTile(
title: Text('Qauntity : ${_items[position].quantity}',
style: TextStyle(fontWeight: FontWeight.bold)),
),
ListTile(
title: Text('Category : ${_items[position].category}',
style: TextStyle(fontWeight: FontWeight.bold)),
),
ListTile(
title: Text('Units : ${_items[position].unit}',
style: TextStyle(fontWeight: FontWeight.bold)),
),
ListTile(
title: Text('Locations: ${_items[position].location}',
style: TextStyle(fontWeight: FontWeight.bold)),
),
],
));
},
);
}
}
答案 0 :(得分:0)
来自https://github.com/tekartik/sqflite/issues/78#issuecomment-465916400
您可以使用mapListToCsv
函数将List<Inventory>
转换为csv
代码片段以将表导出到csv
var result = await db.query('MyTable');
var csv = mapListToCsv(result);
mapListToCsv函数https://github.com/tekartik/sqflite_more/blob/de853083cdbb977f8417970c4ea012de47a9cbcc/sqflite_porter/lib/utils/csv_utils.dart
import 'package:csv/csv.dart';
/// Convert a map list to csv
String mapListToCsv(List<Map<String, dynamic>> mapList,
{ListToCsvConverter converter}) {
if (mapList == null) {
return null;
}
converter ??= const ListToCsvConverter();
var data = <List>[];
var keys = <String>[];
var keyIndexMap = <String, int>{};
// Add the key and fix previous records
int _addKey(String key) {
var index = keys.length;
keyIndexMap[key] = index;
keys.add(key);
for (var dataRow in data) {
dataRow.add(null);
}
return index;
}
for (var map in mapList) {
// This list might grow if a new key is found
var dataRow = List(keyIndexMap.length);
// Fix missing key
map.forEach((key, value) {
var keyIndex = keyIndexMap[key];
if (keyIndex == null) {
// New key is found
// Add it and fix previous data
keyIndex = _addKey(key);
// grow our list
dataRow = List.from(dataRow, growable: true)..add(value);
} else {
dataRow[keyIndex] = value;
}
});
data.add(dataRow);
}
return converter.convert(<List>[]
..add(keys)
..addAll(data));
}