Class Csv
- All Implemented Interfaces:
AutoCloseable
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.
For an extended overview, see Csv Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoiddeleteColumn(int index)Deletes the column at zero-based indexindex.voiddeleteColumnByName(String columnName)Deletes the column named bycolumnName.voiddeleteRow(int index)Deletes the data row at zero-based indexindex.booleanControls whether leading and trailing whitespace is removed from values returned byGetCellandGetCellByName.getCell(int row, int col)Returns the contents of the cell at data rowrowand columncol.getCellByName(int rowIndex, String columnName)Returns the contents of the cell at data rowrowIndexin the column named bycolumnName.getColumnName(int index)Returns the original, untrimmed name of the column at zero-based indexindex.booleangetCrlf()Controls the line endings used bySaveFile,SaveFile2,SaveToString, andSaveToSb.Specifies the single character used to separate fields within each CSV record.booleanControls whether double quotation marks have their standard CSV meaning when reading and writing data.booleanControls whether a backslash causes the following character to be treated literally while parsing CSV data.booleanIndicates whether the first record is a column-name row rather than a data row.intReturns the zero-based index of the column named bycolumnName, or-1if no matching column exists.intgetNumCols(int row)Returns the number of fields in the data row at zero-based indexrow.intThe number of columns in the first row of the CSV.intThe number of data rows in the CSV.Provides optional keywords for uncommon CSV-processing requirements.Specifies the date format used when converting Excel date cells from an.xlsxworksheet to CSV text.voidinsertColumn(int index)Inserts one empty field into each existing row and, when present, into the column-name row.voidClears the current contents and loads CSV data from the file specified bypath.voidClears the current contents and loads CSV data from the file specified byfilename.voidloadFromString(String csvData)Clears the current contents and loads the CSV text contained incsvData.booleanrowMatches(int rowIndex, String matchPattern, boolean caseSensitive)Compares the complete data row at zero-based indexrowIndexwith the wildcard pattern inmatchPattern.voidWrites the entire CSV to the file specified bypath.voidWrites the entire CSV to the file specified byfilename.voidsaveToSb(StringBuilder sb)Clearssband writes the entire CSV document into it.Returns the entire CSV document as a string.voidsetAutoTrim(boolean value)Sets theAutoTrimproperty; seegetAutoTrim().voidSets the cell at zero-based data rowrowand columncoltocontent.voidsetCellByName(int rowIndex, String columnName, String contentStr)Sets the cell at zero-based data rowrowIndexin the column named bycolumnNametocontentStr.voidsetColumnName(int index, String columnName)Sets the name of the column at zero-based indexindextocolumnName.voidsetCrlf(boolean value)Sets theCrlfproperty; seegetCrlf().voidsetDelimiter(String value)Sets theDelimiterproperty; seegetDelimiter().voidsetEnableQuotes(boolean value)Sets theEnableQuotesproperty; seegetEnableQuotes().voidsetEscapeBackslash(boolean value)Sets theEscapeBackslashproperty; seegetEscapeBackslash().voidsetHasColumnNames(boolean value)Sets theHasColumnNamesproperty; seegetHasColumnNames().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsetXlsxDateFormat(String value)Sets theXlsxDateFormatproperty; seegetXlsxDateFormat().voidsortByColumn(String columnName, boolean ascending, boolean caseSensitive)Sorts the data rows using the values in the column named bycolumnName.voidsortByColumnIndex(int index, boolean ascending, boolean caseSensitive)Sorts the data rows using the values in the column at zero-based indexindex.voidxlsxGetSheets(Zip xlsx, StringTable sheetNames)Gets the worksheet names contained in an Excel.xlsxworkbook.voidxlsxLoadSheet(Zip zip, String sheetName)Loads a worksheet from an Excel.xlsxworkbook into this CSV object.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Csv
public Csv()Creates a newCsvobject.
-
-
Method Details
-
getAutoTrim
public boolean getAutoTrim()Controls whether leading and trailing whitespace is removed from values returned byGetCellandGetCellByName.- 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.- Returns:
- the value of the
AutoTrimproperty
- When
-
setAutoTrim
public void setAutoTrim(boolean value)Sets theAutoTrimproperty; seegetAutoTrim().- Parameters:
value- the new value
-
getCrlf
public boolean getCrlf()Controls the line endings used bySaveFile,SaveFile2,SaveToString, andSaveToSb.- 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.
- Returns:
- the value of the
Crlfproperty
- When
-
setCrlf
public void setCrlf(boolean value)Sets theCrlfproperty; seegetCrlf().- Parameters:
value- the new value
-
getDelimiter
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
Csvobject.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
|, andEnableQuoteshas not been explicitly set,EnableQuotesdefaults tofalse.- Returns:
- the value of the
Delimiterproperty
-
setDelimiter
Sets theDelimiterproperty; seegetDelimiter().- Parameters:
value- the new value (notnull)
-
getEnableQuotes
public boolean getEnableQuotes()Controls whether double quotation marks have their standard CSV meaning when reading and writing data. The default value istrue.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.- Returns:
- the value of the
EnableQuotesproperty
-
setEnableQuotes
public void setEnableQuotes(boolean value)Sets theEnableQuotesproperty; seegetEnableQuotes().- Parameters:
value- the new value
-
getEscapeBackslash
public boolean getEscapeBackslash()Controls whether a backslash causes the following character to be treated literally while parsing CSV data. The default value isfalse.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\tproduce the literal charactersn,r, andt; 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.
- Returns:
- the value of the
EscapeBackslashproperty
-
setEscapeBackslash
public void setEscapeBackslash(boolean value)Sets theEscapeBackslashproperty; seegetEscapeBackslash().- Parameters:
value- the new value
-
getHasColumnNames
public boolean getHasColumnNames()Indicates whether the first record is a column-name row rather than a data row. The default value isfalse.Set this property to
truebefore loading CSV data when the first record contains column names. Chilkat then stores the first record as the column names and excludes it fromNumRowsand zero-based data-row indexing.Changing this property to
trueafter data has already been loaded does not reinterpret the first data row as column names. CallingSetColumnNameautomatically changes this property totrue.Methods that address a column by name require this property to be
trueand require the requested name to exist.- Returns:
- the value of the
HasColumnNamesproperty
-
setHasColumnNames
public void setHasColumnNames(boolean value)Sets theHasColumnNamesproperty; seegetHasColumnNames().- Parameters:
value- the new value
-
getNumColumns
public int getNumColumns()The number of columns in the first row of the CSV. WhenHasColumnNamesistrue, 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
GetNumColsto obtain the number of columns in a particular data row.- Returns:
- the value of the
NumColumnsproperty (read-only)
-
getNumRows
public int getNumRows()The number of data rows in the CSV.- When
HasColumnNamesistrue, 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.
- Returns:
- the value of the
NumRowsproperty (read-only)
- When
-
getUncommonOptions
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.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
getXlsxDateFormat
Specifies the date format used when converting Excel date cells from an.xlsxworksheet to CSV text.The default value is
mm-dd-yy. Other formats included/m/yyyy,m/d/yyyy, and similar Excel-style date-format patterns.- Returns:
- the value of the
XlsxDateFormatproperty
-
setXlsxDateFormat
Sets theXlsxDateFormatproperty; seegetXlsxDateFormat().- Parameters:
value- the new value (notnull)
-
deleteColumn
public void deleteColumn(int index)Deletes the column at zero-based indexindex. The deletion is applied to the column-name row, when present, and to each data row that contains that column.indexmust not be negative. For predictable deletion,indexshould be less thanNumColumns.- Parameters:
index- theindexargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
deleteColumnByName
Deletes the column named bycolumnName. This method requiresHasColumnNamesto betrue.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.
- Parameters:
columnName- thecolumnNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
deleteRow
public void deleteRow(int index)Deletes the data row at zero-based indexindex. The first data row is at index0, regardless of whether a column-name row exists.indexmust be between0andNumRows - 1.- Parameters:
index- theindexargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getCell
Returns the contents of the cell at data rowrowand columncol.Row and column indexes are zero-based. The upper-left data cell is at row
0, column0. WhenHasColumnNamesistrue, the header row is not included in the row index.- If
rowis negative or beyond the available data rows,nullis returned andLastMethodSuccessisfalse. - If
colis negative,nullis returned andLastMethodSuccessisfalse. - If
rowis valid butcolis beyond the number of fields in that row, an empty string is returned andLastMethodSuccessistrue.
When
AutoTrimistrue, surrounding whitespace is removed from the returned value without changing the stored cell content.- Parameters:
row- therowargumentcol- thecolargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- If
-
getCellByName
Returns the contents of the cell at data rowrowIndexin the column named bycolumnName. Row indexing begins at0and excludes the header row.This method requires
HasColumnNamesto betrue. Column-name matching is case-sensitive. Surrounding whitespace is removed from column names for lookup purposes, socolumnNameshould contain the trimmed name. If duplicate lookup names exist, the last matching column is used.If the row or column name is invalid,
nullis returned andLastMethodSuccessisfalse. WhenAutoTrimistrue, surrounding whitespace is removed from the returned cell value.- Parameters:
rowIndex- therowIndexargumentcolumnName- thecolumnNameargument (notnull)- Returns:
- the result, or
nullif not found (no exception is thrown in that case)
-
getColumnName
Returns the original, untrimmed name of the column at zero-based indexindex. The first column is at index0.- Parameters:
index- theindexargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getIndex
Returns the zero-based index of the column named bycolumnName, or-1if no matching column exists.This method requires
HasColumnNamesto betrue. Matching is case-sensitive. Surrounding whitespace is removed from loaded column names for lookup purposes, socolumnNameshould contain the trimmed name. If duplicate lookup names exist, the index of the last matching column is returned.- Parameters:
columnName- thecolumnNameargument (notnull)- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
getNumCols
public int getNumCols(int row)Returns the number of fields in the data row at zero-based indexrow. This is useful for CSV data containing rows of different lengths.Returns
0ifrowis negative or beyond the available data rows.- Parameters:
row- therowargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
insertColumn
public void insertColumn(int index)Inserts one empty field into each existing row and, when present, into the column-name row.indexis a zero-based insertion position.- If
indexis within a row, the empty field is inserted before that position. - If
indexis 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.
indexmust not be negative.- Parameters:
index- theindexargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- If
-
loadFile
Clears the current contents and loads CSV data from the file specified bypath. SetHasColumnNames,Delimiter,EnableQuotes, and other parsing options before calling this method.On Windows, the file is decoded using the current Windows ANSI code page. Use
LoadFile2when 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.
- Parameters:
path- thepathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadFile2
Clears the current contents and loads CSV data from the file specified byfilename.charsetspecifies 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.
- Parameters:
filename- thefilenameargument (notnull)charset- thecharsetargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadFromString
Clears the current contents and loads the CSV text contained incsvData. SetHasColumnNames,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
csvDatarather than necessarily causing the load to fail.- Parameters:
csvData- thecsvDataargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
rowMatches
Compares the complete data row at zero-based indexrowIndexwith the wildcard pattern inmatchPattern. The row is compared as one delimited record using the currentDelimiter; 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
caseSensitiveistrue, matching is case-sensitive. - When
caseSensitiveisfalse, matching is case-insensitive. AutoTrimdoes not alter the row used for matching.
Returns
truewhen the row matchesmatchPattern. Returnsfalsewhen it does not match or whenrowIndexis outside the available data rows.- Parameters:
rowIndex- therowIndexargumentmatchPattern- thematchPatternargument (notnull)caseSensitive- thecaseSensitiveargument- Returns:
- the result; this method never throws
ChilkatException
- The asterisk character (
-
saveFile
Writes the entire CSV to the file specified bypath.On Windows, the text is encoded using the current Windows ANSI code page. Use
SaveFile2when 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.- Parameters:
path- thepathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
saveFile2
Writes the entire CSV to the file specified byfilename.charsetspecifies 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.
- Parameters:
filename- thefilenameargument (notnull)charset- thecharsetargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
saveToSb
Clearssband writes the entire CSV document into it.Record endings are controlled by
Crlf.sbcontains a line ending after the final record.- Parameters:
sb- thesbargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
saveToString
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 result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setCell
Sets the cell at zero-based data rowrowand columncoltocontent.The CSV grows as needed. If
rowis 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. PassingNumRowsasrowappends a new data row.contentmay contain delimiters, quotation marks, CR, and LF whenEnableQuotesistrue; Chilkat applies the necessary CSV quoting when the data is saved.rowandcolmust not be negative.- Parameters:
row- therowargumentcol- thecolargumentcontent- thecontentargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setCellByName
Sets the cell at zero-based data rowrowIndexin the column named bycolumnNametocontentStr.This method requires
HasColumnNamesto betrueand requirescolumnNameto 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.
contentStrmay contain delimiters, quotation marks, CR, and LF whenEnableQuotesistrue.- Parameters:
rowIndex- therowIndexargumentcolumnName- thecolumnNameargument (notnull)contentStr- thecontentStrargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setColumnName
Sets the name of the column at zero-based indexindextocolumnName. The first column is at index0.Calling this method automatically sets
HasColumnNamestotrue. It can therefore be used on an empty object to create the column-name row.indexmust not be negative.For reliable name-based access, use unique column names without surrounding whitespace.
- Parameters:
index- theindexargumentcolumnName- thecolumnNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
sortByColumn
Sorts the data rows using the values in the column named bycolumnName. The column-name row is not moved.- When
ascendingistrue, rows are sorted in ascending order. - When
ascendingisfalse, rows are sorted in descending order. - When
caseSensitiveistrue, comparisons are case-sensitive. - When
caseSensitiveisfalse, comparisons are case-insensitive.
Values are compared as strings, not as numbers or dates. For example, ascending order places
10before2. 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
HasColumnNamesto betrueandcolumnNameto name an existing column.- Parameters:
columnName- thecolumnNameargument (notnull)ascending- theascendingargumentcaseSensitive- thecaseSensitiveargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- When
-
sortByColumnIndex
public void sortByColumnIndex(int index, boolean ascending, boolean caseSensitive)Sorts the data rows using the values in the column at zero-based indexindex. The column-name row, when present, is not moved.- When
ascendingistrue, rows are sorted in ascending order. - When
ascendingisfalse, rows are sorted in descending order. - When
caseSensitiveistrue, comparisons are case-sensitive. - When
caseSensitiveisfalse, 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.
- Parameters:
index- theindexargumentascending- theascendingargumentcaseSensitive- thecaseSensitiveargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- When
-
xlsxGetSheets
Gets the worksheet names contained in an Excel.xlsxworkbook.xlsxis aZipobject containing the already-opened.xlsxfile.sheetNamesreceives the worksheet names.
- Parameters:
xlsx- thexlsxargument (notnull)sheetNames- thesheetNamesargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
xlsxLoadSheet
Loads a worksheet from an Excel.xlsxworkbook into this CSV object.zipis aZipobject containing the already-opened.xlsxfile.sheetNameis the worksheet name.- Pass an empty string in
sheetNameto load the workbook's default worksheet.
The
XlsxDateFormatproperty controls the text format used for Excel date cells.- Parameters:
zip- thezipargument (notnull)sheetName- thesheetNameargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-