View Source CSV.Encoding.Encoder (CSV v3.0.2)

The Encoder CSV module takes a table stream and transforms it into RFC 4180 compliant stream of lines for writing to a CSV File or other IO.

Link to this section Summary

Functions

Encode a table stream into a stream of RFC 4180 compliant CSV lines for writing to a file or other IO.

Link to this section Types

@type encode_options() ::
  {:separator, char()}
  | {:escape_character, char()}
  | {:headers, [String.t() | atom()] | boolean()}
  | {:delimiter, String.t()}
  | {:force_escaping, boolean()}
  | {:escape_formulas, boolean()}

Link to this section Functions

Link to this function

encode(stream, options \\ [])

View Source
@spec encode(Enumerable.t(), [encode_options()]) :: Enumerable.t()

Encode a table stream into a stream of RFC 4180 compliant CSV lines for writing to a file or other IO.

options

Options

These are the options:

  • :separator – The separator token to use, defaults to ?,. Must be a codepoint (syntax: ? + your separator token).
  • :delimiter – The delimiter token to use, defaults to "\r\n".
  • :headers – When set to true, uses the keys of the first map as the first element in the stream. All subsequent elements are the values of the maps. When set to a list, will use the given list as the first element in the stream and order all subsequent elements using that list. When set to false (default), will use the raw inputs as elements. When set to anything but false, all elements in the input stream are assumed to be maps.
  • :escape_formulas – Escape formulas to prevent CSV Injection.

examples

Examples

Convert a stream of rows with cells into a stream of lines:

iex> [~w(a b), ~w(c d)]
iex> |> CSV.Encoding.Encoder.encode
iex> |> Enum.take(2)
["a,b\r\n", "c,d\r\n"]

Convert a stream of maps into a stream of lines:

iex> [%{"a" => 1, "b" => 2}, %{"a" => 3, "b" => 4}]
iex> |> CSV.Encoding.Encoder.encode(headers: true)
iex> |> Enum.to_list()
["a,b\r\n", "1,2\r\n", "3,4\r\n"]

Convert a stream of rows with cells with escape sequences into a stream of lines:

iex> [["a\nb", "\tc"], ["de", "\tf\""]]
iex> |> CSV.Encoding.Encoder.encode(separator: ?\t, delimiter: "\n")
iex> |> Enum.take(2)
["\"a\nb\"\t\"\tc\"\n", "de\t\"\tf\"\"\"\n"]