Merhaba arkadaşlar bu makalemizde DBGrid nesnesindeki verileri excel dosyasına aktaracağız.
Formumuza 1 adet DBGrid, 1 adet Button ekleyelim. Ayrıca formumuza 1 er adet DataSource, ADOQuery ekleyelim.
Şekil 1
Şekil 2
unit excel_Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Data.Win.ADODB, Vcl.StdCtrls,ComObj;
type
TForm1 = class(TForm)
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
btnSaveExcel: TButton;
procedure FormCreate(Sender: TObject);
procedure btnSaveExcelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Left:=(Screen.Width-Width) div 2;
Top:=(Screen.Height-Height) div 2;
AdoQuery1.Close;
AdoQuery1.SQL.Clear;
AdoQuery1.SQL.Add('Select * From Employee' ) ;
AdoQuery1.Active := True ;
end;
procedure TForm1.btnSaveExcelClick(Sender: TObject);
var
xls, wb, ws, vv: variant;
i, j, k: integer;
fName: string;
fDosya: textfile;
begin
xls := CreateOleObject('Excel.Sheet');
wb := xls.Application.WorkBooks.Add;
ws := wb.Sheets.Add;
ADOQuery1.DisableControls;
ADOQuery1.First;
for i := 1 to ADOQuery1.RecordCount do
begin
for j := 1 to ADOQuery1.Fields.Count do
begin
//sutun isimlerini yaziyoruz.
if i = 1 then
ws.Cells(i, j) := ADOQuery1.Fields.Fields[j - 1].FieldName;
vv := ADOQuery1.Fields.Fields[j - 1].Value;
ws.Cells(i + 1, j) := vv;
//font boyutunu belirliyoruz.
wb.ActiveSheet.Rows[i+1].Font.Size:=20;
end;
ADOQuery1.Next;
end;
//excel satir ve satir arka plan rengini degistiriyoruz.
for k:= 1 to ADOQuery1.RecordCount+1 do
if k mod 2=0 then
begin
wb.ActiveSheet.Rows[k].Font.Color := clFuchsia;
wb.ActiveSheet.Rows[k].Interior.Color := ColorToRGB(clCream);
end
else
begin
wb.ActiveSheet.Rows[k].Font.Color := clBlue;
wb.ActiveSheet.Rows[k].Interior.Color := ColorToRGB(clAqua);
end;
//sutun font style ve rengini ayarliyoruz.
wb.ActiveSheet.Rows[1].Font.Color := clMaroon;
wb.ActiveSheet.Rows[1].Font.Bold:=True;
wb.ActiveSheet.Rows[1].Font.Size:=24;
for j := 1 to ADOQuery1.Fields.Count do
wb.ActiveSheet.Columns[j].ColumnWidth:= 20;
//xls.visible:=false;
ADOQuery1.EnableControls;
//excel dosyasini kaydediyoruz.
fName:='D:\Data\employee.xlsx';
wb.SaveAs(fName);
xls.Application.Quit;
ShowMessage(fName + ' dosyasi basari sekilde kaydedildi!');
end;
end.
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN
0 comments:
Yorum Gönder