Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read and write CSV in a way similar to NET FileHelpers?

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:

http://secretgeek.net/csv_trouble.asp

like image 433
José Eduardo Avatar asked Jan 31 '11 17:01

José Eduardo


People also ask

Can you read and write to a CSV file at the same time?

You can do open("data. csv", "rw") , this allows you to read and write at the same time. So will this help me modify the data?

How do I process a CSV file in C#?

C# CSV read data into objectsGlobalization; using CsvHelper; using var streamReader = File. OpenText("users. csv"); using var csvReader = new CsvReader(streamReader, CultureInfo. CurrentCulture); var users = csvReader.


2 Answers

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

enter image description here

like image 141
Warren P Avatar answered Oct 11 '22 00:10

Warren P


It's pretty basic, but TStringList has Delimiter, DelimitedText, and QuoteChar 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.

like image 22
Craig Stuntz Avatar answered Oct 10 '22 22:10

Craig Stuntz