Dart CSV Writing

拟墨画扇 提交于 2021-02-10 22:22:11

问题


Hey so I haven't really messed around with it too much, but I was wondering if there was actually a way (before I go down a neverending rabbit hole) to read and write to CSV files in Dart/Flutter? I need to write to the files, not necessarily read them, and I'm willing to go to quite extreme lengths to do so. Any library works, built-in functions are even better. Any and all help is appreciated!


回答1:


Use this package csvfrom https://pub.dartlang.org/packages/csv.

If you have a List<List<dynamic>> items that needs to convert into csv,

String csv = const ListToCsvConverter().convert(yourListOfLists);

If you want to write the csv to a file,

    /// Write to a file
    final directory = await getApplicationDocumentsDirectory();
    final pathOfTheFileToWrite = directory.path + "/myCsvFile.csv"
    File file = await File(pathOfTheFileToWrite);
    file.writeAsString(csv);

Also, if you want to read a csv file directly into list<list<dynamic>>

final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(UTF8.decoder).transform(csvCodec.decoder).toList();



回答2:


According to new packages and guidelines(2019) use following code

package csvfrom https://pub.dartlang.org/packages/csv.

If you have a List<List<dynamic>> items that needs to convert into csv,

String csv = const ListToCsvConverter().convert(yourListOfLists);

Then you can write the string to a file using file operations.

file.writeAsString('$csv');

Also, if you want to read a csv file directly into list<list<dynamic>>

final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();


来源:https://stackoverflow.com/questions/54319498/dart-csv-writing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!