3

I have been searching to import csv to database in flutter way. But unfortunately, I cannot find articles related to this case. So I wonder if there is a way to import csv to database. If yes, how can I achieve that? For my case, I open the file picker and want to import csv file. I can easily do it in Kotlin way but not in a flutter way. I would appreciate any help.

aminography
  • 21,986
  • 13
  • 70
  • 74
kinesis
  • 373
  • 1
  • 4
  • 15
  • use https://pub.dev/packages/sqflite - most likely execute `db.insert` in a loop - one `insert` per row – pskink Nov 06 '19 at 07:22
  • I use sqlite, but how can I read contents and add them in sqlite database? In Kotlin I read with headLine(BufferedReader(file)) and remove "," and save in a array and insert to database. How can I achieve that way in Flutter since its been only 1 month that I started learning Flutter. – kinesis Nov 06 '19 at 08:25
  • see `File.openRead()` and `LineSplitter` – pskink Nov 06 '19 at 08:34
  • OK, I will take a look – kinesis Nov 06 '19 at 08:45
  • more here: https://fluttermaster.com/how-to-read-file-using-dart/ - i forgot that for small files you can use `File.readAsLines()` – pskink Nov 06 '19 at 08:48
  • btw, does it have to be csv file? why not a normal [sqlite dump](https://www.sqlitetutorial.net/sqlite-dump/)? – pskink Nov 06 '19 at 09:00
  • Yes it need to be CSV, because I need to import some csv files as Master to check Received Item. – kinesis Nov 06 '19 at 09:40

1 Answers1

6

Well, it's not straightforward.

You'd normally use something like https://pub.dev/packages/csv or https://pub.dev/packages/spreadsheet_decoder in order to parse CSV.

So it'd look something like:

final input = new File('documents/file.csv').openRead();

Then convert it to the list:

final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();

After you did that, you'd normally have a function that is going to do a bulk update.

First, create a database

Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

Then you could use some helper method like mentioned here => https://stackoverflow.com/a/56507307/1737811 in order to populate the database fields with your result.

That way you'd pass your tablename, and of course your List containing the values from the CSV that you've just decoded.

mutantkeyboard
  • 1,614
  • 1
  • 16
  • 44