Csv Lua Reference Documentation

chilkat.Csv

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Csv

Read, edit, sort, and write CSV or delimiter-separated data in memory.

Chilkat.Csv is a practical in-memory table class for working with CSV and other delimiter-separated text formats. It can load CSV data from files or strings, access cells by row/column index or column name, manage header rows, insert and delete rows or columns, sort records, search for matching rows, and write the result back using configurable delimiters, quoting rules, character encodings, and line endings.

In-memory CSV table

Load CSV data, modify cells, add rows, delete rows or columns, and write the updated table back to a file or string.

Header and named columns

Use a header row to access fields by column name instead of only by numeric column index.

Cell and row operations

Read and update individual cells, insert columns, remove data, find matching rows, and sort the table as needed.

Delimiter control

Work with comma-separated data or other delimiter-separated formats by configuring the delimiter character.

Quoting and output formatting

Control quoted fields, forced quoting, output line endings, explicit character encodings, and UTF-8 BOM emission.

Excel worksheet loading

Load worksheet data from an opened .xlsx ZIP container when CSV-style access to spreadsheet content is needed.

Common pattern: Load CSV data, specify whether the first row is a header, access or modify cells by index or column name, perform any row, column, search, or sort operations, then save the table using the delimiter, charset, quoting, BOM, and line-ending settings required by the target system.

Object Creation

local chilkat = require("chilkat")

local csv = chilkat.Csv.new()
local csv = chilkat.Csv.new()

Creates the object (chilkat.Csv() does the same). Lua's garbage collector frees it when it is no longer referenced; csv:dispose() frees it at once, and in Lua 5.4 and later local csv <close> = chilkat.Csv.new() frees it when the block ends. Calling a method of a disposed object raises an error.

Errors

A method that fails returns nil followed by the error text, as io.open does: local body, err = csv:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.

Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.

Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (csv.verbose_logging = true) and methods use the colon (csv:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.

Properties

AutoTrim
-- boolVal is a boolean
local boolVal = csv.auto_trim
csv.auto_trim = boolVal

Controls whether leading and trailing whitespace is removed from values returned by GetCell and GetCellByName.

  • When true, surrounding whitespace such as spaces and tabs is removed from returned cell values.
  • When false, returned cell values are not trimmed. This is the default.

This property does not modify the cell contents stored in the CSV and does not change the text written by the save methods. It also does not trim the names returned by GetColumnName.

top
Crlf
-- boolVal is a boolean
local boolVal = csv.crlf
csv.crlf = boolVal

Controls the line endings used by SaveFile, SaveFile2, SaveToString, and SaveToSb.

  • When true, records are terminated with CRLF. This is the default.
  • When false, records are terminated with LF.

The original line-ending style of loaded data is not preserved. The selected line ending is used for all output records, including the final record.

top
DebugLogFilePath
-- strVal is a string
local strVal = csv.debug_log_file_path
csv.debug_log_file_path = strVal

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
Delimiter
-- strVal is a string
local strVal = csv.delimiter
csv.delimiter = strVal

Specifies the single character used to separate fields within each CSV record. The default value is a comma (,).

Although this property has a string type, only the first character of a non-empty value is used. Assigning an empty string does not clear or reset the current delimiter.

If the delimiter has not been explicitly set, Chilkat detects it while loading the first CSV data and updates this property with the detected character. The detection may examine more than the first record. Once selected or detected, the delimiter remains in effect for subsequent loads performed by the same object. To load data that uses a different delimiter, explicitly set this property before loading or use a new Csv object.

A semicolon (;) is commonly used in locales where a comma is used as the decimal separator.

Creating a new CSV: Set this property before adding rows or columns when a delimiter other than comma is required.

Vertical-bar delimiter: If this property is explicitly set to |, and EnableQuotes has not been explicitly set, EnableQuotes defaults to false.

top
EnableQuotes
-- boolVal is a boolean
local boolVal = csv.enable_quotes
csv.enable_quotes = boolVal
Introduced in version 9.5.0.71

Controls whether double quotation marks have their standard CSV meaning when reading and writing data. The default value is true.

When true, a quoted field is treated as one field even when it contains the delimiter, CR, or LF. A double quotation mark inside a quoted field is represented by two consecutive double quotation marks. Fields created by the application are quoted automatically when required.

Chilkat retains whether a field loaded from CSV text was quoted, so quotation marks that were not strictly required may remain when the CSV is saved again.

When false, quotation marks are ordinary characters and do not protect delimiters or line endings. Do not disable quoting when field values can contain the delimiter, quotation marks, CR, or LF, because such values cannot be represented or round-tripped reliably as ordinary delimited text.

More Information and Examples
top
EscapeBackslash
-- boolVal is a boolean
local boolVal = csv.escape_backslash
csv.escape_backslash = boolVal
Introduced in version 9.5.0.44

Controls whether a backslash causes the following character to be treated literally while parsing CSV data. The default value is false.

When true, examples include:

  • \, represents a literal delimiter character.
  • \\ represents one backslash.
  • \" represents a literal double quotation mark.

This is not C-style escape decoding. For example, \n, \r, and \t produce the literal characters n, r, and t; they do not produce a line feed, carriage return, or tab.

Normal CSV quoting is still used when output fields contain delimiters or line endings.

top
HasColumnNames
-- boolVal is a boolean
local boolVal = csv.has_column_names
csv.has_column_names = boolVal

Indicates whether the first record is a column-name row rather than a data row. The default value is false.

Set this property to true before loading CSV data when the first record contains column names. Chilkat then stores the first record as the column names and excludes it from NumRows and zero-based data-row indexing.

Changing this property to true after data has already been loaded does not reinterpret the first data row as column names. Calling SetColumnName automatically changes this property to true.

Methods that address a column by name require this property to be true and require the requested name to exist.

More Information and Examples
top
LastErrorHtml
-- strVal is a string (read-only)
local strVal = csv.last_error_html

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
-- strVal is a string (read-only)
local strVal = csv.last_error_text

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
-- strVal is a string (read-only)
local strVal = csv.last_error_xml

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
-- boolVal is a boolean
local boolVal = csv.last_method_success
csv.last_method_success = boolVal

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
NumColumns
-- intVal is an integer (read-only)
local intVal = csv.num_columns

The number of columns in the first row of the CSV. When HasColumnNames is true, this is the number of column names in the header row.

CSV rows may contain different numbers of fields. Therefore, this property is not necessarily the maximum number of columns found in any row. Use GetNumCols to obtain the number of columns in a particular data row.

top
NumRows
-- intVal is an integer (read-only)
local intVal = csv.num_rows

The number of data rows in the CSV.

  • When HasColumnNames is true, the column-name row is not included.
  • Interior blank rows are included.
  • Empty or whitespace-only rows following the last non-empty row are not included.

top
UncommonOptions
-- strVal is a string
local strVal = csv.uncommon_options
csv.uncommon_options = strVal
Introduced in version 9.5.0.88

Provides optional keywords for uncommon CSV-processing requirements. The default value is an empty string, and this property should normally remain empty. To enable more than one option, use a comma-separated list.

The following keywords are defined:

  • QuotedCells (v9.5.0.96) — Encloses every data cell in double quotation marks when writing the CSV.
  • QuotedColumnNames (v9.5.0.96) — Encloses every column name in double quotation marks when writing the CSV.
  • EMIT_BOM (v9.5.0.93) — Writes a UTF-8 byte order mark when saving a UTF-8 encoded CSV file.

top
VerboseLogging
-- boolVal is a boolean
local boolVal = csv.verbose_logging
csv.verbose_logging = boolVal

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
-- strVal is a string (read-only)
local strVal = csv.version

Version of the component/library, such as "10.1.0"

More Information and Examples
top
XlsxDateFormat
-- strVal is a string
local strVal = csv.xlsx_date_format
csv.xlsx_date_format = strVal
Introduced in version 11.3.0

Specifies the date format used when converting Excel date cells from an .xlsx worksheet to CSV text.

The default value is mm-dd-yy. Other formats include d/m/yyyy, m/d/yyyy, and similar Excel-style date-format patterns.

top

Methods

DeleteColumn
-- index is an integer
-- ok is true, or nil and err on failure
local ok, err = csv:delete_column(index)

Deletes the column at zero-based index index. The deletion is applied to the column-name row, when present, and to each data row that contains that column.

index must not be negative. For predictable deletion, index should be less than NumColumns.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
DeleteColumnByName
-- column_name is a string
-- ok is true, or nil and err on failure
local ok, err = csv:delete_column_by_name(column_name)

Deletes the column named by column_name. This method requires HasColumnNames to be true.

Column-name matching is case-sensitive. Surrounding whitespace in a loaded column name is not part of its lookup name. Column names should be unique to avoid ambiguous lookup and deletion behavior.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
DeleteRow
-- index is an integer
-- ok is true, or nil and err on failure
local ok, err = csv:delete_row(index)

Deletes the data row at zero-based index index. The first data row is at index 0, regardless of whether a column-name row exists.

index must be between 0 and NumRows - 1.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetCell
-- row is an integer
-- col is an integer
-- str is a string, or nil and err on failure
local str, err = csv:get_cell(row, col)

Returns the contents of the cell at data row row and column col.

Row and column indexes are zero-based. The upper-left data cell is at row 0, column 0. When HasColumnNames is true, the header row is not included in the row index.

  • If row is negative or beyond the available data rows, nil is returned and LastMethodSuccess is false.
  • If col is negative, nil is returned and LastMethodSuccess is false.
  • If row is valid but col is beyond the number of fields in that row, an empty string is returned and LastMethodSuccess is true.

When AutoTrim is true, surrounding whitespace is removed from the returned value without changing the stored cell content.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetCellByName
-- row_index is an integer
-- column_name is a string
-- str is a string, or nil and err on failure
local str, err = csv:get_cell_by_name(row_index, column_name)

Returns the contents of the cell at data row row_index in the column named by column_name. Row indexing begins at 0 and excludes the header row.

This method requires HasColumnNames to be true. Column-name matching is case-sensitive. Surrounding whitespace is removed from column names for lookup purposes, so column_name should contain the trimmed name. If duplicate lookup names exist, the last matching column is used.

If the row or column name is invalid, nil is returned and LastMethodSuccess is false. When AutoTrim is true, surrounding whitespace is removed from the returned cell value.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
GetColumnName
-- index is an integer
-- str is a string, or nil and err on failure
local str, err = csv:get_column_name(index)

Returns the original, untrimmed name of the column at zero-based index index. The first column is at index 0.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
GetIndex
-- column_name is a string
-- n is an integer
local n = csv:get_index(column_name)

Returns the zero-based index of the column named by column_name, or -1 if no matching column exists.

This method requires HasColumnNames to be true. Matching is case-sensitive. Surrounding whitespace is removed from loaded column names for lookup purposes, so column_name should contain the trimmed name. If duplicate lookup names exist, the index of the last matching column is returned.

top
GetNumCols
-- row is an integer
-- n is an integer
local n = csv:get_num_cols(row)

Returns the number of fields in the data row at zero-based index row. This is useful for CSV data containing rows of different lengths.

Returns 0 if row is negative or beyond the available data rows.

top
InsertColumn
-- index is an integer
-- ok is true, or nil and err on failure
local ok, err = csv:insert_column(index)
Introduced in version 9.5.0.89

Inserts one empty field into each existing row and, when present, into the column-name row. index is a zero-based insertion position.

  • If index is within a row, the empty field is inserted before that position.
  • If index is at or beyond the end of a row, one empty field is appended to that row.
  • Rows are not padded to a common width, so ragged rows remain ragged.
  • Calling this method on an object with no rows and no column-name row has no effect.

index must not be negative.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
LoadFile
-- path is a string
-- ok is true, or nil and err on failure
local ok, err = csv:load_file(path)

Clears the current contents and loads CSV data from the file specified by path. Set HasColumnNames, Delimiter, EnableQuotes, and other parsing options before calling this method.

On Windows, the file is decoded using the current Windows ANSI code page. Use LoadFile2 when the character encoding must be specified explicitly.

The existing CSV contents are cleared before the file is opened. Therefore, a failure such as a missing file does not preserve the previously loaded data.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
LoadFile2
-- filename is a string
-- charset is a string
-- ok is true, or nil and err on failure
local ok, err = csv:load_file2(filename, charset)

Clears the current contents and loads CSV data from the file specified by filename. charset specifies the character encoding used by the file.

Set HasColumnNames, Delimiter, EnableQuotes, and other parsing options before calling this method.

See Supported Charsets for the encoding names recognized by Chilkat.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
LoadFromString
-- csv_data is a string
-- ok is true, or nil and err on failure
local ok, err = csv:load_from_string(csv_data)

Clears the current contents and loads the CSV text contained in csv_data. Set HasColumnNames, Delimiter, EnableQuotes, and other parsing options before calling this method.

Passing an empty string successfully clears the CSV. The parser is permissive; for example, an unterminated quoted field extends through the end of csv_data rather than necessarily causing the load to fail.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
RowMatches
-- row_index is an integer
-- match_pattern is a string
-- case_sensitive is a boolean
-- flag is true or false
local flag = csv:row_matches(row_index, match_pattern, case_sensitive)

Compares the complete data row at zero-based index row_index with the wildcard pattern in match_pattern. The row is compared as one delimited record using the current Delimiter; the pattern may therefore include or span field separators.

  • The asterisk character (*) may appear any number of times and matches zero or more characters.
  • When case_sensitive is true, matching is case-sensitive.
  • When case_sensitive is false, matching is case-insensitive.
  • AutoTrim does not alter the row used for matching.

Returns true when the row matches match_pattern. Returns false when it does not match or when row_index is outside the available data rows.

Returns true or false: an answer, not a success flag.

top
SaveFile
-- path is a string
-- ok is true, or nil and err on failure
local ok, err = csv:save_file(path)

Writes the entire CSV to the file specified by path.

On Windows, the text is encoded using the current Windows ANSI code page. Use SaveFile2 when the output encoding must be specified explicitly.

Record endings are controlled by Crlf, and the final record is also followed by the selected line ending.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SaveFile2
-- filename is a string
-- charset is a string
-- ok is true, or nil and err on failure
local ok, err = csv:save_file2(filename, charset)

Writes the entire CSV to the file specified by filename. charset specifies the output character encoding, and Chilkat converts the CSV text to that encoding while saving.

Record endings are controlled by Crlf, and the final record is also followed by the selected line ending.

See Supported Charsets for the encoding names recognized by Chilkat.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
SaveToSb
-- sb is a chilkat.StringBuilder
-- ok is true, or nil and err on failure
local ok, err = csv:save_to_sb(sb)
Introduced in version 9.5.0.93

Clears sb and writes the entire CSV document into it.

Record endings are controlled by Crlf. sb contains a line ending after the final record.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SaveToString
-- str is a string, or nil and err on failure
local str, err = csv:save_to_string()

Returns the entire CSV document as a string.

Record endings are controlled by Crlf. The returned string includes a line ending after the final record. The line-ending style originally loaded into the object is not preserved.

Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetCell
-- row is an integer
-- col is an integer
-- content is a string
-- ok is true, or nil and err on failure
local ok, err = csv:set_cell(row, col, content)

Sets the cell at zero-based data row row and column col to content.

The CSV grows as needed. If row is beyond the current last row, intervening rows are created as empty rows. Within the target row, intervening columns are created as empty cells. Other rows are not padded, so the resulting CSV may contain rows with different numbers of fields. Passing NumRows as row appends a new data row.

content may contain delimiters, quotation marks, CR, and LF when EnableQuotes is true; Chilkat applies the necessary CSV quoting when the data is saved. row and col must not be negative.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SetCellByName
-- row_index is an integer
-- column_name is a string
-- content_str is a string
-- ok is true, or nil and err on failure
local ok, err = csv:set_cell_by_name(row_index, column_name, content_str)

Sets the cell at zero-based data row row_index in the column named by column_name to content_str.

This method requires HasColumnNames to be true and requires column_name to match an existing column name. Matching is case-sensitive and uses the trimmed lookup form of the stored column name. A missing column is not created.

The data-row collection grows as needed. content_str may contain delimiters, quotation marks, CR, and LF when EnableQuotes is true.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
SetColumnName
-- index is an integer
-- column_name is a string
-- ok is true, or nil and err on failure
local ok, err = csv:set_column_name(index, column_name)

Sets the name of the column at zero-based index index to column_name. The first column is at index 0.

Calling this method automatically sets HasColumnNames to true. It can therefore be used on an empty object to create the column-name row. index must not be negative.

For reliable name-based access, use unique column names without surrounding whitespace.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
SortByColumn
-- column_name is a string
-- ascending is a boolean
-- case_sensitive is a boolean
-- ok is true, or nil and err on failure
local ok, err = csv:sort_by_column(column_name, ascending, case_sensitive)

Sorts the data rows using the values in the column named by column_name. The column-name row is not moved.

  • When ascending is true, rows are sorted in ascending order.
  • When ascending is false, rows are sorted in descending order.
  • When case_sensitive is true, comparisons are case-sensitive.
  • When case_sensitive is false, comparisons are case-insensitive.

Values are compared as strings, not as numbers or dates. For example, ascending order places 10 before 2. Empty or missing sort cells appear first in ascending order and last in descending order. The sort is not stable, so rows having equal sort values may change relative order.

This method requires HasColumnNames to be true and column_name to name an existing column.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
SortByColumnIndex
-- index is an integer
-- ascending is a boolean
-- case_sensitive is a boolean
-- ok is true, or nil and err on failure
local ok, err = csv:sort_by_column_index(index, ascending, case_sensitive)
Introduced in version 9.5.0.83

Sorts the data rows using the values in the column at zero-based index index. The column-name row, when present, is not moved.

  • When ascending is true, rows are sorted in ascending order.
  • When ascending is false, rows are sorted in descending order.
  • When case_sensitive is true, comparisons are case-sensitive.
  • When case_sensitive is false, comparisons are case-insensitive.

Values are compared as strings, not as numbers or dates. Empty and missing sort cells are treated as empty strings. They appear first in ascending order and last in descending order. The sort is not stable, so rows having equal sort values may change relative order.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top
XlsxGetSheets
-- xlsx is a chilkat.Zip
-- sheet_names is a chilkat.StringTable
-- ok is true, or nil and err on failure
local ok, err = csv:xlsx_get_sheets(xlsx, sheet_names)
Introduced in version 11.3.0

Gets the worksheet names contained in an Excel .xlsx workbook.

  • xlsx is a Zip object containing the already-opened .xlsx file.
  • sheet_names receives the worksheet names.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

More Information and Examples
top
XlsxLoadSheet
-- zip is a chilkat.Zip
-- sheet_name is a string
-- ok is true, or nil and err on failure
local ok, err = csv:xlsx_load_sheet(zip, sheet_name)
Introduced in version 11.3.0

Loads a worksheet from an Excel .xlsx workbook into this CSV object.

  • zip is a Zip object containing the already-opened .xlsx file.
  • sheet_name is the worksheet name.
  • Pass an empty string in sheet_name to load the workbook's default worksheet.

The XlsxDateFormat property controls the text format used for Excel date cells.

Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.

top