Mega Code Archive

 
Categories / Delphi / Files
 

How to Parse TAB Delimited Files in Delphi

Title: How to Parse TAB Delimited Files 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: Create a TStringList object ("sl" in the code below) to hold the TAB delimited file, Use the LoadFromFile method of the TStringList to fill the list with the lines of text in a specified TAB delimited file, Use another instance of the TStringList ("slRow" in the code below) to process each TAB separated line in "sl", Use the DelimitedText property to set all the strings in "slRow" object in a single string. The Set the Delimiter property to #9 which is the character control sequence for the TAB character. 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;