Mega Code Archive

 
Categories / Delphi / ADO Database
 

Exporting any TDataSet to a comma delimited ASCII file

Title: Exporting any TDataSet to a comma delimited ASCII file Question: How to export any kind of TDataSet to a comma delimited ASCII file? Answer: unit Unit1; interface uses db, classes, dialogs,sysutils; {procedure DataSetToASCII - exports records from the ADataSet TDataSet to specified ASCIIFile text file. Fields are separated by provided Delimiter character. Only fields with Tag property set to 0 (default) are included in exporting. Records are separated with line break characters and ordered as in the ADataSet. If QuoteStrings is True then fields of type ftString,ftMemo,ftFmtMemo,ftFixedChar and ftWideString are quoted in the output file - thanks Bill Artemik for this very important tip} procedure DataSetToASCII(const ADataSet: TDataSet; const ASCIIFile: TFileName; const Delimiter: Char; const QuoteStrings: Boolean); implementation procedure DataSetToASCII(const ADataSet: TDataSet; const ASCIIFile: TFileName; const Delimiter: Char; const QuoteStrings: Boolean); var tmpList: TStringList; i,LastIndex: LongInt; AsciiRecord: String; begin tmpList:= TStringList.Create; try with ADataSet do begin LastIndex:= Fields.Count - 1; First; while not EOF do begin AsciiRecord:= ''; for i := 0 to LastIndex do if Fields.Fields[i].Tag = 0 then begin if QuoteStrings and (Fields.Fields[i].DataType in [ftString,ftMemo,ftFmtMemo,ftFixedChar,ftWideString]) then AsciiRecord:= AsciiRecord + QuotedStr(Fields.Fields[i].AsString) else AsciiRecord:= AsciiRecord + Fields.Fields[i].AsString; if i AsciiRecord:= AsciiRecord + Delimiter; end; tmpList.Append(AsciiRecord); Next end end; try tmpList.SaveToFile(ASCIIFile) except ShowMessage('Could not save table to specified file: ' + ASCIIFile) end; finally tmpList.Free; end; end; end.