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.

7
  • use pub.dev/packages/sqflite - most likely execute db.insert in a loop - one insert per row Commented Nov 6, 2019 at 7: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. Commented Nov 6, 2019 at 8:25
  • see File.openRead() and LineSplitter Commented Nov 6, 2019 at 8:34
  • OK, I will take a look Commented Nov 6, 2019 at 8:45
  • more here: fluttermaster.com/how-to-read-file-using-dart - i forgot that for small files you can use File.readAsLines() Commented Nov 6, 2019 at 8:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please tell me more about implementing some helper method? I don't get it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.