1. Computing & Technology

Discuss in my forum

How to Parse TAB Delimited Files in Delphi

and Display in the TStringGrid Delphi control

By , About.com Guide

Parse Tab Delimited file in Delphi

Parse Tab Delimited file in Delphi

TAB delimited text (ASCII) files contain lines of code with each chunk (column) of data (string) separated by the TAB character.

Most database and spreadsheet programs are able to read or save data in a delimited format.

Displaying TAB delimited Files in a TStringGrid Control

To display the TAB delimited files in a TStringGrid Delphi control use the next idea:
  1. Create a TStringList object ("sl" in the code below) to hold the TAB delimited file,
  2. Use the LoadFromFile method of the TStringList to fill the list with the lines of text in a specified TAB delimited file,
  3. Use another instance of the TStringList ("slRow" in the code below) to process each TAB separated line in "sl",
  4. Use the DelimitedText property to set all the strings in "slRow" object in a single string. The
  5. Set the Delimiter property to #9 which is the character control sequence for the TAB character.
  6. For each string chunk in "slRow" write the string in the TStringGrid a cell.
Note: Delphi's TStringGrid control represents a grid control designed to simplify the handling of strings and associated objects.

Here's the code:

 procedure TForm1.ProcessTabDelimitedFile(const fileName: TFileName) ;
 var
   sl, slRow : TStringList;
   line, col : integer;
 begin
   //will load the TAB delimited TXT here
   sl := TStringList.Create;
   //will process each TAB delimited line here
   slRow := TStringList.Create;
   slRow.StrictDelimiter := true; 
   slRow.Delimiter := #9; //TAB
   try
     //load the tab delimited txt file
     sl.LoadFromFile(fileName) ;
     StringGrid1.RowCount := sl.Count;
 
     //for each tab delimited line
     for line := 0 to -1 + sl.Count do
     begin
       //"load" the line into a stringlist
       slRow.DelimitedText := sl[line];
       StringGrid1.Rows[line].Assign(slRow);
     end;
   finally
     slRow.Free;
     sl.Free;
   end;
 end;
 
Delphi tips navigator:
» Implement the On Item Checked Event for the TListView Delphi control
« Convert RGB to TColor or How to Get More TColor values for Delphi

©2012 About.com. All rights reserved.

A part of The New York Times Company.