Tuesday, April 04, 2006

Exporting to Text File

I was in dire need to find out a function which exports table to text file. While googling around, i found out some interesting codes which I would like to share with you all.


Jeremy Collin's Code:
const
  InvalidFieldTypes = [ftMemo, ftBlob, ftGraphic, ftFmtMemo,
ftParadoxOle,
    ftDBaseOle, ftTypedBinary];

function TableToText(const tbl : TDataset; FileName : string;
  Delimiter : Char; FieldNames : boolean): boolean;
var
  f             : TextFile;
  i             : integer;
  bmk   : TBookmark;
begin
  if not(tbl.Active) then
    tbl.Open;
  bmk := tbl.GetBookMark;

  AssignFile(f, Filename);
  ReWrite(f);
  try
    with tbl do begin
      if FieldNames then begin  //write field names to top of file
        for i := 0 to FieldDefs.Count - 1 do
          if not(FieldDefs[i].DataType  in InvalidFieldTypes) then begin
            Write(f, UpperCase(FieldDefs[i].Name));

            if i < FieldDefs.Count - 1 then
              Write(f, Delimiter);
          end;
        WriteLn(f);
      end;

      //write field data
      First;
      while not Eof do begin
        for i := 0 to FieldDefs.Count - 1 do begin
          if not(FieldDefs[i].DataType in InvalidFieldTypes) then begin
            Write(f, '"' + Fields[i].AsString + '"');
            if i < FieldDefs.Count - 1 then
              Write(f, Delimiter);
          end;
        end;
        WriteLn(f);
        Next;
      end;
      Result := True;
    end;
  finally
    tbl.GotoBookmark(bmk);
    tbl.FreeBookmark(bmk);
    CloseFile(f);
  end;
end;
--


URL

No comments: