Anyone know how I can import/export csv, txt files in a way similar to NET FileHelpers, but using Delphi, taking spaces and quotes into account and handling traditional CSV escaping rules in a manner similar to the way CSV escaping works in Excel?
ref. link http://www.filehelpers.com/
If your answer tends to be: "why this lazy guy dont write a simple CSV parser", consider this 5 minutes reading and then you will know why CSV parsing is not trivial:
My functions
It's pretty basic, but
TStringList
hasDelimiter
,DelimitedText
, andQuoteChar
properties, which address some of these issues.Updated to add, per comments: Don't be tempted by the
CommaText
property, which has some surprising limitations for backwards compatibility with archaic versions of Delphi.Here some code I wrote that reads CSV files, it handles carriage returns inside quotes as well.
I wrote a Dataset (TTable-like object) for Jedi project called TJvCsvDataSet that follows all CSV parsing rules in a way similar to the CSV parsing rules used by Excel and various database and report tools that import and export CSVs.
You can install JVCL, drop a TJvCsvDataSet on your form.
It also contains a stream class that will very quickly load a file on disk, and parse it line by line, using the correct escape rules required for CSV files, even files that include carriage-return/line-feed codes encoded within a field.
You just drop it on your form, and set the FieldDefs property like this:
CsvFieldDef=ABC:%,DEF:#,GHI:$,....
There are special codes for integer, floating point, iso date-time, and other fields. It even allows you to map a wide-string field to a utf8 field in a CSV file.
There is a designtime property editor to save you from having to declare the CSV Field Defs using the syntax above, instead you can just pick visually what the column types are.
If you don't set up a CSV Field Def, it merely maps whatever exists in the file to string-type fields.
Jedi JVCL: http://jvcl.delphi-jedi.org/
JvCsvDataSet Docs:
http://help.delphi-jedi.org/unit.php?Id=3107
http://help.delphi-jedi.org/item.php?Id=174896
My framework has code for this in the CsiTextStreamsUnt.pas file (see http://www.csinnovations.com/framework_delphi.htm)
Following the VCL TXMLTransform logic, I wrote a TCsvTransform class helper that translates a .csv format structure to /from a TClientDataSet.
For more details about TCsvTransform, cf http://didier.cabale.free.fr/delphi.htm#uCsvTransform.
NB: I set the same field type symbols as Warren's TJvCsvDataSet