Chilkat.Csv Class Overview

Chilkat.Csv provides a simple in-memory CSV table for loading, editing, sorting, querying, and saving comma-separated or delimiter-separated data. It supports column names, quoted fields, alternate delimiters, backslash escaping, character encodings, CSV output formatting, and limited Excel .xlsx sheet loading through a Chilkat Zip object.

What the Class Is Used For

Use Chilkat.Csv when an application needs to read a CSV file, access or modify individual cells, work with optional column names, delete or insert rows and columns, sort rows by column values, or write the CSV back to a file, string, or StringBuilder. The class handles common CSV details such as delimiters, quoted fields, embedded CR/LF characters, delimiter characters inside quoted cells, and character-set conversion during file load/save operations.

Load and Save CSV Load from files or strings, then save to files, strings, or a StringBuilder.
Cell and Column Access Get or set cells by row/column index, or by column name when column names are enabled.
CSV Formatting Control Control delimiters, quotes, CRLF vs LF line endings, trimming, BOM emission, and output quoting behavior.
Excel Sheet Import List sheets and load a worksheet from an already opened .xlsx file using a Chilkat Zip object.

Typical Workflow

  1. Create a Csv object.
  2. Set parsing options before loading, especially HasColumnNames, Delimiter, EnableQuotes, and EscapeBackslash.
  3. Load CSV data with LoadFile, LoadFile2, or LoadFromString.
  4. Inspect structure using NumRows, NumColumns, GetNumCols, GetColumnName, and GetIndex.
  5. Read or update cells using GetCell, SetCell, GetCellByName, or SetCellByName.
  6. Optionally sort, delete rows/columns, insert columns, or match rows using SortByColumn, DeleteRow, InsertColumn, or RowMatches.
  7. Save the result with SaveFile, SaveFile2, SaveToString, or SaveToSb.
  8. Check LastErrorText after any failed load, save, sort, delete, insert, or update operation.

Core Concepts

Concept Meaning Important Members
Rows and Columns CSV data is treated as a table. Rows and columns are zero-based, with the top-left data cell at 0,0. GetCell, SetCell, NumRows, NumColumns
Column Names The first record can be treated as column names rather than data. HasColumnNames, GetCellByName, SetCellByName, GetIndex
Delimiter The character separating fields in each record. The default is comma, but semicolons and other delimiters are also possible. Delimiter, LoadFile, SaveToString
Quoted Fields Double quotes allow delimiter characters, CR, LF, and other special characters to be treated as normal cell text. EnableQuotes, SetCell, SaveFile
Character Encoding CSV files can be loaded and saved using a specified charset. LoadFile2, SaveFile2
Excel Sheet Conversion A sheet from an opened .xlsx file can be loaded into the CSV object. XlsxGetSheets, XlsxLoadSheet, XlsxDateFormat

Core Properties

Property Purpose Guidance
HasColumnNames Indicates that the first record contains column names rather than data. Set to true before loading when the CSV has a header row.
Delimiter Defines the character used to separate fields. Defaults to comma. If not explicitly set, Chilkat detects the delimiter when loading. Set it before adding rows/columns when creating a new CSV with a non-comma delimiter.
EnableQuotes Controls whether double quotes are treated as CSV quote characters. Default is true. When true, quoted content may include CR, LF, delimiter characters, and quotes according to CSV parsing rules.
EscapeBackslash Controls whether backslash is treated as an escape character. Default is false. Enable only when working with CSV data that uses backslash escaping.
AutoTrim Trims whitespace from both ends of strings returned by cell-get methods. Applies to GetCell and GetCellByName.
Crlf Chooses line endings when saving CSV. If true, saved output uses CRLF. If false, saved output uses LF.
NumRows Number of data rows. If column names are present, the header row is not counted. Trailing empty whitespace-only lines after the last non-empty row are not counted.
NumColumns Number of columns in the first row. If HasColumnNames is true, this may refer to the row containing column names.
XlsxDateFormat Standard date format used when converting Excel .xlsx spreadsheets to CSV. Default is mm-dd-yy. Can be changed to formats such as d/m/yyyy or m/d/yyyy.
UncommonOptions Comma-separated keywords for uncommon behavior. Usually left empty. Supports options such as QuotedCells, QuotedColumnNames, and EMIT_BOM.
LastErrorText Diagnostic text for the last method or property access. Check after failures or unexpected behavior. Diagnostic information may be available regardless of success or failure.

Loading CSV Data

Source Method Behavior
File, ANSI assumed LoadFile Loads a CSV file assuming ANSI characters.
File with explicit charset LoadFile2 Loads a CSV file using the specified character encoding, such as utf-8, windows-1252, or another supported charset.
In-memory string LoadFromString Loads a CSV document from a string variable.
Excel worksheet XlsxLoadSheet Loads a named sheet from an already opened .xlsx file represented by a Chilkat Zip object. Pass an empty sheet name to load the first/default sheet.
Header-row setup: Set HasColumnNames = true before loading if the first CSV record contains column names. This prevents the header row from being treated as data.
Delimiter detection: If Delimiter is not explicitly set, Chilkat detects the delimiter when loading. This is useful for semicolon-delimited CSV files often used in locales where comma is a decimal separator.

Saving CSV Data

Output Target Method Behavior
File, ANSI output SaveFile Saves the CSV to a file using ANSI character encoding.
File with explicit charset SaveFile2 Saves the CSV to a file using the specified character encoding.
StringBuilder SaveToSb Clears the supplied StringBuilder and writes the entire CSV into it.
String SaveToString Returns the entire CSV as a string.
Line endings: Set Crlf to choose output line endings. True emits CRLF; false emits LF.
Special characters: Cells may contain CRLF, double quotes, and delimiter characters. Save methods automatically double-quote fields with special characters when needed.

Cell Access and Editing

Task Method Notes
Get a cell by row and column index GetCell Returns the content at row, col. Indexing starts at 0.
Set a cell by row and column index SetCell Sets the content of a cell. Content may include CRLF, double quotes, and the delimiter character.
Get a cell by column name GetCellByName Same as GetCell, but the column is specified by name.
Set a cell by column name SetCellByName Same as SetCell, but the column is specified by name.
Get number of columns in a row GetNumCols Returns the number of columns for a specific row. Returns 0 if the row index is beyond the number of rows.
AutoTrim behavior: If AutoTrim is true, returned cell strings from GetCell and GetCellByName are trimmed of whitespace on both ends.

Column Names

Task Method / Property Behavior
Enable header row HasColumnNames Set true before loading when the first record contains column names.
Set column name SetColumnName Sets the name of the Nth column. The first column is index 0.
Get column name GetColumnName Returns the name of the Nth column.
Find column index GetIndex Returns the index for a column name, or -1 if no such column exists.
Delete column by name DeleteColumnByName Deletes a column specified by name.
Get/set cells by name GetCellByName, SetCellByName Uses the column name instead of a numeric column index.

Rows, Columns, and Structure Changes

Task Method Behavior
Delete row DeleteRow Deletes the entire Nth row. The first row is index 0.
Delete column by index DeleteColumn Deletes the Nth column. The first column is index 0.
Delete column by name DeleteColumnByName Deletes a column specified by column name.
Insert empty column InsertColumn Inserts a new empty column before the Nth column.

Sorting and Row Matching

Task Method Behavior
Sort by column name SortByColumn Sorts rows using the contents of a named column. Supports ascending or descending order and case-sensitive or case-insensitive sorting.
Sort by column index SortByColumnIndex Sorts rows using the contents of a column index. Supports ascending or descending order and case-sensitive or case-insensitive sorting.
Match entire row against wildcard pattern RowMatches Compares an entire row to a wildcard pattern. The * character matches zero or more characters. Matching can be case-sensitive or case-insensitive.

Quoting, Escaping, and Delimiters

Feature Property Important Detail
Delimiter-separated fields Delimiter Default is comma. If not explicitly set, the delimiter is detected when loading. Set explicitly before creating a new non-comma CSV.
Quoted CSV fields EnableQuotes Default is true. Quoted content may contain delimiter characters, CR, LF, and other special characters.
Backslash escaping EscapeBackslash Default is false. Set true when input or output should treat backslash as an escape character.
Vertical bar delimiter behavior Delimiter, EnableQuotes If the delimiter is explicitly set to vertical bar | and EnableQuotes was never explicitly set, then EnableQuotes defaults to false.
Creating CSV with a custom delimiter: Set Delimiter before adding rows or columns. This is especially important when creating semicolon-delimited or pipe-delimited output.

UncommonOptions

Keyword Added Effect
QuotedCells v9.5.0.96 Forces all cell contents to be double-quoted when emitting CSV to a file or string.
QuotedColumnNames v9.5.0.96 Forces all column names to be double-quoted when emitting CSV to a file or string.
EMIT_BOM v9.5.0.93 Emits the UTF-8 byte order mark when writing CSV to a file, assuming the CSV is written using UTF-8.
Multiple options: When more than one uncommon behavior is needed, set UncommonOptions to a comma-separated list of keywords.

Excel .xlsx Support

Chilkat.Csv can load worksheet data from an Excel .xlsx file when the file has already been opened with a Chilkat Zip object.

Task Method / Property Behavior
List sheet names XlsxGetSheets Returns sheet names from the opened .xlsx file into a StringTable.
Load a sheet XlsxLoadSheet Loads a named sheet into the CSV object. Pass an empty string for the first or default sheet.
Choose date output format XlsxDateFormat Controls the standard date format used when converting Excel dates to CSV. Default is mm-dd-yy.
XLSX input object: Both XlsxGetSheets and XlsxLoadSheet expect a Chilkat Zip object containing the already opened .xlsx file.

Method Summary by Category

Category Methods Purpose
Load CSV LoadFile, LoadFile2, LoadFromString Load CSV data from a file or in-memory string.
Save CSV SaveFile, SaveFile2, SaveToString, SaveToSb Save CSV data to a file, string, or StringBuilder.
Cell access GetCell, SetCell, GetCellByName, SetCellByName Read or write cell values by index or column name.
Column names GetColumnName, SetColumnName, GetIndex Manage and look up column names.
Structure changes DeleteRow, DeleteColumn, DeleteColumnByName, InsertColumn Remove rows or columns, or insert an empty column.
Row and column inspection GetNumCols, NumRows, NumColumns Inspect the table shape and per-row column counts.
Sorting and matching SortByColumn, SortByColumnIndex, RowMatches Sort rows or match an entire row against a wildcard pattern.
Excel conversion XlsxGetSheets, XlsxLoadSheet List and load sheets from an opened Excel .xlsx workbook.

Diagnostics and Troubleshooting

Problem Area Member What to Check
Load or save failed LastErrorText Check file path, permissions, character encoding, delimiter settings, and whether the CSV data is valid for the chosen quoting/escaping options.
Header row appears as data HasColumnNames Set HasColumnNames = true before loading the CSV.
Unexpected number of rows NumRows Remember that the column-name row is not counted as a data row, and trailing whitespace-only lines after the last non-empty row are not counted.
Unexpected number of columns NumColumns, GetNumCols NumColumns reports the first row’s column count. Use GetNumCols to inspect a specific row.
Cell text includes extra spaces AutoTrim Set AutoTrim to true if returned cell values should be trimmed.
Quoted text not parsed as expected EnableQuotes, EscapeBackslash Confirm whether the input uses standard CSV quoting, backslash escaping, or a custom delimiter that affects quote handling.
Column name lookup fails GetIndex, GetColumnName Confirm the column name exists and that the CSV was loaded with HasColumnNames correctly set.
Excel date output is not desired format XlsxDateFormat Set the desired date format before loading the Excel sheet.

Common Pitfalls

Pitfall Better Approach
Setting HasColumnNames after loading. Set it before calling LoadFile, LoadFile2, or LoadFromString.
Creating a semicolon- or pipe-delimited CSV without setting the delimiter first. Set Delimiter before adding rows or columns.
Using LoadFile for non-ANSI files. Use LoadFile2 and specify the correct charset, such as utf-8.
Using SaveFile when UTF-8 or another charset is required. Use SaveFile2 with the desired charset.
Assuming every row has the same number of columns. Use GetNumCols for row-specific column counts.
Expecting NumRows to include the header row. When HasColumnNames is true, the header row is not counted as a data row.
Forgetting that pipe delimiters can alter default quote behavior. When using |, explicitly set EnableQuotes to the behavior you want.

Best Practices

Recommendation Reason
Set parser options before loading. Options such as HasColumnNames, Delimiter, EnableQuotes, and EscapeBackslash affect how input is parsed.
Use LoadFile2 and SaveFile2 for known encodings. Explicit charsets avoid ANSI assumptions and improve interoperability.
Use column names for readable table logic. GetCellByName, SetCellByName, and SortByColumn make code less dependent on numeric column positions.
Use GetIndex before relying on a column name. It returns -1 when the named column is not present.
Use Crlf to control output line endings. This makes saved CSV output predictable across Windows and Unix-style environments.
Use UncommonOptions for forced quoting or UTF-8 BOM output. QuotedCells, QuotedColumnNames, and EMIT_BOM handle uncommon CSV formatting needs.
Use SaveToSb when composing CSV inside larger generated text. It writes the full CSV into a StringBuilder without going through a file.
Check LastErrorText after failures. It provides the most useful diagnostic detail for load, save, parse, sort, delete, insert, and Excel sheet operations.

Summary

Chilkat.Csv is a practical in-memory CSV table class for reading, editing, sorting, and writing delimiter-separated data. It supports header rows, named columns, cell access by index or name, row/column deletion, column insertion, row matching, configurable delimiters, quoted fields, explicit character encodings, output line-ending control, forced quoting options, UTF-8 BOM emission, and Excel worksheet loading through an opened .xlsx ZIP container.

The most important practical guidance is to set parsing options before loading, use explicit charsets for non-ANSI files, use column names when available, and set Delimiter before creating new CSV data with a non-comma delimiter.