Read CSV file in Dart

  • Read line by line in the CSV file

This example opens the CSV file in a stream and reads the line by line. Reads the file line by line in chunks to avoid loading entire files in memory and is useful for loading larger files using stream.

import 'dart:io';
import 'dart:convert';

 void main() async {
   try {
  final file =await  File('emp.csv').openRead();

    await file
     .transform(new LineSplitter())
     .forEach((l) => print('$l'));
   catch (e) {
     print('Reading CSV file error: $e');

First, a File read operation is asynchronous, so added the async keyword to the main() function

  • Open a file for reading Parse the file and transform it with utf8.decoder,
    • Use one more transformer, which takes LineSplitter, which takes comma as default delimiter. Returns an array of field data.
    • Use forEach to iterate and print the data)

Write a Dart Array object into a CSV file

import 'dart:io';

import 'package:csv/CSV.dart';

void main() {
  // Initialize data with Array of headers and data
  final data = [
    ['id','Name', 'Salary'],
    [1,' Eric', 5000],
    [2, 'Brew', 7000],
    [3, 'Bob', 3000],
  // Create a file 
  final file = File('output.csv');
  // Convert the array of objects into a CSV string
  final csvStr = ListToCsvConverter().convert(data);
  // Write string into a file

In this example,

  • Imported csv and io m modules
  • Initialize a list of objects where each object is data, First object is a header.
  • Create a file object with the output file
  • ListToCsvConverter().convert() converts the dart object into CSV string format.
  • Finally, use file.writeAsString() to write a CSV string into a file

On running the above code, Generates output.csv file successfully