Poor Man’s CSV Export

Recently I came to the point where I had to export the tables of a database as CSV files. While in FireDAC there is TFDDataMove, I wasn’t able to use it as I encountered a bug ┬áin that component that rendered the output useless. (The bug has been fixed by Dmitry the day after I mentioned it, but is not publicly available yet.)

So I wondered how such a simple CSV export can be done with things available in Delphi. Well, here it is:

This method works with any TDataSet descendant.

It uses the Text property of TField to get a string representation of the field value – and this is the point where you can hook in to adjust any fields output to your needs. Let’s say, we have a blob field to export. The OnGetText event handler for that field can look like this:

The CR/LF sequences inside the Base64 coded string are removed because many CSV readers cannot cope with linebreaks inside quotes. As Base64 doesn’t need these linebreaks, we can do this safely in this case, but it might be an issue in others. As it is difficult to give a one-for-all solution for this problem, the OnGetText event is a good place to make the string representation fit your needs.

Next time I will show a similar approach for importing CSV files. Then I will have a closer look on AutoInc fields and references to them. Stay tuned…

Author: Uwe Raabe

Addicted to Pascal/Delphi since the late 70's