How to write CSV in Dart
Encode rows to CSV text, with quoting handled so the output survives a round trip.
Install#
dart pub add csv_plusimport 'package:csv_plus/csv_plus.dart';Encode rows#
final codec = CsvCodec();
final csv = codec.encode([
['name', 'age', 'score'],
['Alice', 30, 95.5],
['Bob', 25, 88.0],
]);Fields that need quoting get quoted. A value containing the delimiter, a quote character or a line break is wrapped and escaped for you, so the result reads back as the same data.
Quoting#
// Quote every field, not just the ones that need it.
final always = CsvCodec(CsvConfig(quoteMode: QuoteMode.always));Writing for Excel#
Excel is particular. It expects a semicolon delimiter in many locales, and without a UTF-8 BOM it mangles non-ASCII text. There is a preset:
final excel = CsvCodec.excel(); // ';' delimiter plus a UTF-8 BOMWriting to a file#
import 'package:csv_plus/io.dart';
await CsvFile.write('out.csv', table);
await CsvFile.append('out.csv', [['Zoe', 41]]);Two-column CSV from a map#
codec.encodeMap({'host': 'localhost', 'port': 8080});
// host,localhost
// port,8080