给你个代码看下
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExcelXP, OleServer, Grids, DBGrids, DB, ADODB;
type
TForm1 = class(TForm)
con1: TADOConnection;
tbl1: TADOTable;
ds1: TDataSource;
dbgrd1: TDBGrid;
exclplctn1: TExcelApplication;
exclwrksht1: TExcelWorksheet;
exclwrkbk1: TExcelWorkbook;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
procedure writedata;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btn1Click(Sender: TObject);
var empty:OleVariant;
begin
try
exclplctn1.Connect;
except
MessageDlg('可能没有安装Excel',mtError,[mbok],0);
abort;
end;
exclplctn1.Visible[0]:=true;
try
empty:=EmptyParam;
exclplctn1.Workbooks.Add(empty,0);
exclwrkbk1.ConnectTo(exclplctn1.Workbooks.Item[exclplctn1.Workbooks.count]);
exclwrkbk1.Activate;
exclwrksht1.ConnectTo((exclwrkbk1.Worksheets[1]as _worksheet));
writedata;
except
exclwrkbk1.Close(xlDoNotSaveChanges);
exclplctn1.Disconnect;
end;
end;
procedure TForm1.writedata;
var col:char;
row,j:integer;
r:string;
begin
with tbl1 do
begin
First;
col:='A';
row:=1;
while not eof do
begin
for j:=0 to Fields.Count-1 do
begin
r:=string(col)+inttostr(row);
exclwrksht1.Range[r,r].Value2:=Fields.Fields[j].Value;
col:=chr(Ord(col)+1);
end;
Inc(row);
col:='A';
Next;
end;
end;
end;
end.