0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【入門】【コピペ可】Dart でcsvファイルを読みこむ

Posted at

やりたいこと

このようなcsvを、List<List<>>型のオブジェクトとして読み込みたい

csvを読み込み、List<List>として取得する

以下は、test.csv というパスに当該のcsvがあることを想定しています。
もちろん、必要に応じてこちらのパスは変更してください。

main.dart
// Import a csv flie
Future<List<List>> csvImport() async {

  final String importPath = 'test.csv';
  final File importFile = File(importPath);
  List<List> importList = [];

  Stream fread = importFile.openRead();

  // Read lines one by one, and split each ','
  await fread.transform(utf8.decoder).transform(LineSplitter()).listen(
    (String line) {
      importList.add(line.split(','));
    },
  ).asFuture();

  return Future<List<List>>.value(importList);
}

void main() async {
  final csv = await csvImport();
  print(csv);
}

実行結果

% dart run main.dart
[[apple, orange]], [[ape, lion]]

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?