Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2543
  • Last Modified:

Export to CSV

Hi
Does anybody have some code for how to export a stringgrid to CSV to be read in Excel
0
koger
Asked:
koger
  • 4
1 Solution
 
ZifNabCommented:
Hi Koger,

Have a look a the free StringGrid :

http://www.tmssoftware.com/advgrid.htm

Regards, Zif.
0
 
ZifNabCommented:
you can of course also use OLE to transfer your data
0
 
ZifNabCommented:
this is also a possible way, if you don't want to use a component or OLE :

procedure TForm1.BitBtn1Click(Sender: TObject);
var F:TextFile;
    i,j : integer;
begin
  AssignFile(F, 'c:\griddata.csv');
  Rewrite(F);
  for i := 0 to stringgrid1.RowCount-1 do
  begin
    for j := 0 to stringgrid1.ColCount-1 do
    begin
      if j = stringgrid1.ColCount-1 then
       Writeln(F,stringgrid1.cells[i,j])
      else
       Write(F,stringgrid1.cells[i,j],',');
    end;
  end;
  CloseFile(F);
end;

Zif.
0
 
kogerAuthor Commented:
Thanks Zifnab, but I would have some source code not a compiled dcu and I can't use OLE.
I don't know the CSV text (i don't have Excel), but what if a cell contains a comma, I guess you should then put a couple of "" around the text, but I don't know.
0
 
ZifNabCommented:
Hi Koger,

Then it's even simpler :

procedure TForm1.Button1Click(Sender: TObject);
var F:TextFile;
    i : integer;
begin
 AssignFile(F, 'c:\griddata.csv');
 Rewrite(F);
 for i := 0 to stringgrid1.RowCount-1 do
 begin
  writeln(F,stringgrid1.Rows[i].CommaText);
 end;
 CloseFile(F);
end;

CommaText does it for you :-) (if a cell contains a comma, the value will be written as...","5,4","...

I tried it, and it imports into Excell without a problem.

Regards, Zif.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now