Einzelnen Beitrag anzeigen

Vader

Registriert seit: 6. Mai 2003
804 Beiträge
 
Delphi 6 Enterprise
 
#23

Re: Inhald eines DBGrid nach Excel exportieren ?

  Alt 21. Jun 2006, 15:39
hallo,

könnte wer den code propieren ob der bei euch funktioniert !!

Delphi-Quellcode:
procedure DBGridToExcel(DBGrid:TDBGrid; StartSpalte, StartZeile:integer);
type TSpalten = array[1..256] of string;

  function CreateSpalten:TSpalten;
  var i, j, x:integer;
      abbruch:boolean;
  begin
    x:=1;
    abbruch:=false;
    j:=0;
    while (j <= 26) and not abbruch do begin
      i:=1;
      while (i <= 26) and not abbruch do begin
        if j = 0 then
          Result[x]:=chr(i+64)
        else
          Result[x]:=chr(j+64)+chr(i+64);
        inc(i);
        inc(x);
        abbruch:=(x > 256);
      end;
      inc(j);
    end;
  end;

var Excel:TExcelApplication;
    i, Zeile, lcid:integer;
    Workbook:_Workbook;
    Sheet, Zelle, Inhalt:Variant;
    Spalten:TSpalten;
begin
  if assigned(DBGrid)
     and assigned(DBGrid.DataSource)
     and assigned(DBGrid.DataSource.DataSet) then
  begin
    if DBGrid.DataSource.DataSet.Active then begin
      Excel:=TExcelApplication.Create(nil);
      try
        lcid:=GetUserDefaultLCID;
        Excel.Connect;
        Excel.Visible[lcid]:=true;
        Excel.UserControl:=true;

        Workbook:=Excel.Workbooks.Add(EmptyParam, lcid);

        Spalten:=CreateSpalten;
        Zeile:=StartZeile;
        for i:=1 to DBGrid.FieldCount do begin
          Inhalt:=DBGrid.Fields[i-1].DisplayName;
          Zelle:=Excel.Cells.Range[
            Spalten[i+StartSpalte-1]+inttostr(Zeile),
            Spalten[i+StartSpalte-1]+inttostr(Zeile)
          ];
          Zelle.Value:=Inhalt;
          Zelle.Font.Bold:=true;
        end;

        DBGrid.DataSource.DataSet.First;
        while not DBGrid.DataSource.DataSet.Eof do begin
          inc(Zeile);
          for i:=1 to DBGrid.FieldCount do begin
            Inhalt:=DBGrid.DataSource.DataSet.FieldByName(
              DBGrid.Fields[i-1].FieldName
            ).AsString;
            Zelle:=Excel.Cells.Range[
              Spalten[i+StartSpalte-1]+inttostr(Zeile),
              Spalten[i+StartSpalte-1]+inttostr(Zeile)
            ];
            Zelle.Value:=Inhalt;
          end;
          DBGrid.DataSource.DataSet.Next;
        end;

        Sheet:=Workbook.ActiveSheet;
        Sheet.Columns[
          Spalten[StartSpalte]+':'+Spalten[StartSpalte+DBGrid.FieldCount]
        ].EntireColumn.AutoFit;

      finally
        Excel.Disconnect;
        Excel.free;
      end;
    end;
  end;
end;


aufruf


DBGridToExcel(DBGrid, 1, 1); mfg vader
  Mit Zitat antworten Zitat