Title: THvHQuery for exporting query to CSV file.
Question: Sometimes you need a quick solution for exporting a TQuery result to a CSV file.
Answer:
Register the next component to your component pallet.
How to use:
You can use the property editor to fill in the filename to write too.
You can specify if you want to write the Fieldnames (CSVHeaders).
You can specify if you want to append to the file.
You have to implement your own error handling strategy for the opening of the file. The propery for returning the FileError is there already.
unit HvHQuery;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables;
type
THvHQuery = class(TQuery)
private
{ Private declarations }
FFileName: string;
FErrorCodeWriteCSV: integer;
FCSVHeaders: boolean;
FErrorCode: integer;
FAppendToCSVFile: boolean;
F:TextFile;
procedure SetCSVHeader(Value: boolean);
procedure SetErrorCode(Value: integer);
procedure WriteCSVHeaders;
procedure WriteCSVValues;
protected
{ Protected declarations }
public
procedure WriteCSVFile;
{ Public declarations }
published
{ Published declarations }
property FileName: string read FFileName write FFileName;
property ErrorCode: integer read FErrorCodeWriteCSV write SetErrorCode;
property CSVHeaders: boolean read FCSVHeaders write SetCSVHeader default False;
property AppendToCSVFile: boolean read FAppendToCSVFile write FAppendToCSVFile default False;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('HvH', [THvHQuery]);
end;
procedure THvHQuery.SetCSVHeader(value: boolean);
begin
FCSVHeaders := Value;
end;
procedure THvHQuery.SetErrorCode(Value: integer);
begin
FErrorCode := Value;
end;
procedure THvHQuery.WriteCSVHeaders;
var
i: integer;
begin
if FCSVHeaders then begin
i := 0;
While i
Write (F, format('"%s"', [Fields[i].FieldName]));
if i Write (F, ';')
else
WriteLn(F);
i := i + 1;
end;
end;
end;
procedure THvHQuery.WriteCSVValues;
var
i: integer;
begin
i := 0;
While i
Write (F, '"' + Fields[i].Text + '"');
if i Write (F, ';')
else
WriteLn(F);
i := i + 1;
end;
end;
procedure THvHQuery.WriteCSVFile;
var
i: integer;
begin
AssignFile(F, FFileName);
if FAppendToCSVFile then
System.Append(F)
else
ReWrite(F);
First;
WriteCSVHeaders;
while not EOF do begin
WriteCSVValues;
Next;
end;
CloseFile(F);
end;
end.