|
| THvHQuery for exporting query to CSV file. | 
|
|---|
| Export a query to a Comma Seperated CSV File. | Product: Delphi 5.x (or higher) | Category: DB-General | Skill Level:
 | Scoring:  | Last Update: 09/09/2003 | Search Keys: delphi delphi3000 article borland vcl code-snippet CSV Query Export Component | Times Scored: 1 | Visits: 4321 | Uploader: Henk van Hoek Company: | Reference: N/A | | | Question/Problem/Abstract:
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 < Fields.Count do begin
Write (F, format('"%s"', [Fields[i].FieldName]));
if i < Fields.Count - 1 then
Write (F, ';')
else
WriteLn(F);
i := i + 1;
end;
end;
end;
procedure THvHQuery.WriteCSVValues;
var
i: integer;
begin
i := 0;
While i < Fields.Count do begin
Write (F, '"' + Fields[i].Text + '"');
if i < Fields.Count - 1 then
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.
|
|
|
| |
Sign up to consume product discounts for Bronze memberships !
|
|
| |
Community Ad of S. Kucherov |
|
| |
|
|
|