If (Pos(Delimiter,s) > 0) OR (Pos(Enclosure,s) > 0) then // Comment this line for enclosure in every fieldsįor I := 0 to DataSet. Result := StringReplace(s,Enclosure,Enclosure Enclosure,) procedure SaveToCSV(DataSet: TDataSet FileName: String) ĭelimiter: Char = ' ' // In order to be automatically recognized in Microsoft Excel use " ", not ","įunction EscapeString(s: string): string You can easily disable this enhancements if not required. This is like the Rob McDonell solution but with some enhancements: header, escape chars, enclosure only when required, and " " separator. You can add options to change the delimiter type or whatever. procedure WriteDataSetToCSV(DataSet: TDataSet, FileName: String) It will work with any TDataSet, not just a TQuery. The original question asked for a solution using a StringList. assignfile (f,'xxxxx.csv') rewrite (f) for j:0 to lines-1 do begin writeln (f.) closefile (f) Reading a CSV It sounds simple : read a line, and take it appart. Stream.Write(sLineBreak, Length(sLineBreak)) reading and writing them is simple : writing to a CSV Write a line with the usual formatting. Stream.Write(OutLine, Length(OutLine) * SizeOf(Char)) You'll need to add your special handling here where OutLine is built Stream := TFileStream.Create('C:\Data\YourFile.csv', fmCreate) This will take care of the easy part: var I'll leave the fancy CSV quoting and special handling to you. You can easily write the output using TFileStream, and get the data using the TQuery.Fields and TQuery.FieldCount properly. You just have to do the work to properly output the CSV content (quoting properly, handling embedded quotes and commas, etc.).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |