procedure ExporttoExl(TheDataset:TDataSet;SheetExcelName:String);
var
XApp:Variant;
sheet:Variant;
r,c:Integer;
q:Integer;
row,col:Integer;
fildName:Integer;
begin
try
begin
XApp:=CreateOleObject('Excel.Application');
XApp.Visible:=true;
end;
except
showmessage('Unable to link with MS Excel, it seems as it is not installed on this system.');
exit;
end;
XApp.WorkBooks.Add(-4167);
//open a new blank workbook
XApp.WorkBooks[1].WorkSheets[1].Name:='Sheet1';
//give any name required to ExcelSheet
sheet:=XApp.WorkBooks[1].WorkSheets['Sheet1'];
for fildName:=0 to TheDataset.FieldCount-1 do
//TheDataset refer to the any dataset holding data
begin
q:=fildName+1;
sheet.Cells[1,q]:=TheDataset.Fields[fildName].FieldName;
// enter the column headings
end;
//now supply the data from table to excel sheet
TheDataset.First;
for r:=0 to TheDataset.RecordCount-1 do
begin
for c:=0 to TheDataset.FieldCount-1 do
begin
row:=r+2;
col:=c+1;
sheet.Cells[row,col]:=TheDataset.Fields[c].AsString;
end;
TheDataset.Next;
end;
//set font attributes of required range if required
XApp.WorkSheets['Sheet1'].Range['A1:AA1'].Font.Bold:=True;
XApp.WorkSheets['Sheet1'].Range['A1:AA1'].Font.Color := clblue;
XApp.WorkSheets['Sheet1'].Range['A1:AA1'].Font.Color := clblue;
XApp.WorkSheets['Sheet1'].Range['A1:K1'].Borders.LineStyle :=13;
// set other attributes as below
XApp.WorkSheets['Sheet1'].Range['A1:K11'].HorizontalAlignment := 3;
// .Borders.LineStyle :=13;
XApp.WorkSheets['Sheet1'].Columns[1].ColumnWidth:=10;
XApp.WorkSheets['Sheet1'].Columns[2].ColumnWidth:=10;
XApp.WorkSheets['Sheet1'].Columns[3].ColumnWidth:=15;
XApp.WorkSheets['Sheet1'].Columns[4].ColumnWidth:=6;
XApp.WorkSheets['Sheet1'].Columns[5].ColumnWidth:=18;
XApp.WorkSheets['Sheet1'].Columns[6].ColumnWidth:=9;
XApp.WorkSheets['Sheet1'].Columns[7].ColumnWidth:=23;
XApp.WorkSheets['Sheet1'].Columns[8].ColumnWidth:=23;
XApp.WorkSheets['Sheet1'].Columns[9].ColumnWidth:=23;
XApp.WorkSheets['Sheet1'].Columns[10].ColumnWidth:=10;
xapp.caption := 'Exported from Demo programmed by SK Arora,the digitiger';
XApp.WorkSheets['Sheet1'].name := 'Exported from ' + SheetExcelName;
//assuming dataset is TTable based its tablename can be given as title of worksheet
//close;
end;