Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Create CSV File

See more CSV Examples

Demonstrates how to create a new CSV file with some simple content.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Csv;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  csv: TCsv;
  csvDoc: string;

begin
  success := False;

  //  This sample code creates a new CSV file (sample.csv)
  //  that contains this content:
  //  
  //  year,color,country,food
  //  2001,red,France,cheese
  //  2005,blue,"United States",hamburger

  csv := TCsv.Create;

  //  Indicate that the 1st row
  //  should be treated as column names:
  csv.HasColumnNames := True;

  success := csv.SetColumnName(0,'year');
  success := csv.SetColumnName(1,'color');
  success := csv.SetColumnName(2,'country');
  success := csv.SetColumnName(3,'food');

  success := csv.SetCell(0,0,'2001');
  success := csv.SetCell(0,1,'red');
  success := csv.SetCell(0,2,'France');
  success := csv.SetCell(0,3,'cheese');

  success := csv.SetCell(1,0,'2005');
  success := csv.SetCell(1,1,'blue');
  success := csv.SetCell(1,2,'United States');
  success := csv.SetCell(1,3,'hamburger');

  //  Write the CSV to a string and display:

  csvDoc := csv.SaveToString();
  WriteLn(csvDoc);

  //  Save the CSV to a file:
  success := csv.SaveFile('out.csv');
  if (success <> True) then
    begin
      WriteLn(csv.LastErrorText);
    end;


  csv.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.