Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Writing CSV

strings.SplitCsv reads comma-separated text (see Split and Join). Writing it has the opposite problem: a field holding a comma or a quote has to be quoted, or the reader splits it in two.

#import "std/strings"
#import "std/containers"
#import "std/fs"
using containers

dim fields as Array( of ustring ) = { "plain", "a,b", !"5\" pipe", " pad" }
print strings.JoinCsvRow( fields )
print strings.JoinCsvRow( fields, ";" )

'' CsvWriter writes rows to any stream; this one is in memory.
dim buffer as fs.MemoryStream
dim w as strings.CsvWriter = strings.CsvWriter( buffer, ",", false )
w.WriteRow( fields )
w.WriteRow( fields )
print "ok? "; w.Finish( ).IsOk( )

'' Reading it back gives the same fields.
var rows = strings.SplitCsv( buffer.ToUtf8Text( ) )
print "rows: "; rows.Count( ); ", third field: "; rows[1].fields[2]

Output

plain,"a,b","5"" pipe"," pad"
plain;a,b;"5"" pipe";" pad"
ok? true
rows:  2, third field: 5" pipe

JoinCsvRow( fields [, separator] ) writes one record. A field is quoted only when it holds the separator, a double quote or a line break, or starts or ends with a space; a quote inside a field is doubled. With ";" as the separator, a,b no longer needs quotes.

CsvWriter writes records to any fs.Stream — a File, a pipe, or a MemoryStream as here. Records end with CR LF, the standard CSV line ending, unless the third argument is false. If a write fails, the writer stops writing and Finish( ) returns the failure.

Whatever JoinCsvRow writes, SplitCsv reads back as the same fields.

Activities

  1. Add a field containing a line break and check that it survives the round trip.
  2. Write the rows to a file with fs.File and Create, then open it in a spreadsheet.