chickadee » csv » make-format

make-format #!optional DELIMITERprocedure

Returns procedures for outputting individual field values, CSV records, and lists of CSV records, where each list is printed on a separate line.

Procedure FORMAT-CELL takes in a value, obtains its string representation via format, and surrounds the string with quotes, if it contains characters that need to be escaped (such as quote characters, the delimiter character, or newlines).

Procedure FORMAT-RECORD takes in a record of type csv-record and returns its string representation, based on the strings produced by FORMAT-CELL and the delimiter character.

Procedure FORMAT-CSV takes in a list of csv-record objects and produces a string representation using FORMAT-RECORD.

Example:

(use csv)

(define-values (fmt-cell fmt-record fmt-csv) (make-format ";"))

(fmt-cell "hello") => "hello"

;; This is quoted because it contains delimiter-characters
(fmt-cell "one;two;three") => "\"one;two;three\""

;; This is quoted because it contains quotes, which are then doubled for escaping
(fmt-cell "say \"hi\"") => "\"say \"\"hi\"\"\""

;; Converts one line at a time (useful when converting data in a streaming manner)
(fmt-record (list->csv-record '("hi there" "let's say \"hello world\" again" "until we are bored")))
=> "hi there;\"let's say \"\"hello world\"\" again\";until we are bored"

;; And an example of how to quickly convert a list of lists 
;; to a CSV string containing the entire CSV file
(fmt-csv (map list->csv-record
              '(("one" "two")
                ("and another \"line\"" "of csv stuff"))))
=> "one;two\r\n\"and another \"\"line\"\"\";of csv stuff\r\n"