Skip to content

ddn.data.csv

This page provides runnable examples for reading and writing CSV using the ddn.data.csv module.


1) Read CSV from a string and parse values

This example reads rows lazily using byRows, skips a header row, and parses numeric fields using fromCsv.

#!/usr/bin/env dub
/+ dub.sdl:
    name "data-csv-read"
    dependency "ddn" version="*"
+/
module examples.data_csv_read;

import std.stdio : writeln, writefln;
import ddn.data.csv;

void main() {
   // Header + two rows
   const csv = "name,qty,price\n" ~
      "apples,2,1.50\n" ~
      "bananas,3,0.75\n";

   double total = 0;
   auto r = byRows(csv);

   // Skip header
   if (!r.empty)
      r.popFront();

   while (!r.empty) {
      auto row = r.front;
      auto qty = fromCsv!long(row[1]);
      auto price = fromCsv!double(row[2]);
      if (qty.isOk && price.isOk)
         total += qty.value * price.value;
      r.popFront();
   }

   writefln("total = %.2f", total);
   // 2*1.50 + 3*0.75 = 5.25
   assert(total > 5.24 && total < 5.26);
}

2) Write CSV to an in-memory sink (with quoting)

This example uses CsvWriter to write rows into a custom sink type. The writer applies RFC 4180 quoting rules.

#!/usr/bin/env dub
/+ dub.sdl:
    name "data-csv-write"
    dependency "ddn" version="*"
+/
module examples.data_csv_write;

import std.stdio : writeln;
import std.string : startsWith;
import ddn.data.csv;

static class Sink {
   string data;
   void put(const(char)[] s) {
      data ~= s;
   }
}

void main() {
   auto s = new Sink();
   auto w = CsvWriter!(Sink)(s);

   // A field containing a comma will be quoted.
   assert(w.writeRow(["id", "name"]).isOk);
   assert(w.writeRow(["1", "Doe, Jane"]).isOk);
   w.flush();

   writeln(s.data);
   assert(s.data.startsWith("id,name"));

   // Read it back.
   writeln("Read-back:");
   foreach (row; byRows(s.data))
      writeln("  ", row[0].toString(), " | ", row[1].toString());
}

3) Customize dialect options

You can adjust delimiter/newline policy and other behavior via CsvDialect.

#!/usr/bin/env dub
/+ dub.sdl:
    name "data-csv-dialect"
    dependency "ddn" version="*"
+/
module examples.data_csv_dialect;

import std.stdio : writeln;
import ddn.data.csv;

static class Sink {
   string data;
   void put(const(char)[] s) { data ~= s; }
}

void main() {
   auto d = CsvDialect.init;
   d.delimiter = ';';
   d.newlinePolicy = NewlinePolicy.FORCE_LF;

   auto s = new Sink();
   auto w = CsvWriter!(Sink)(s, d);
   assert(w.writeRow(["a", "b"]).isOk);
   assert(w.writeRow(["1", "2"]).isOk);
   w.flush();

   writeln(s.data);
}