用D5的Server组控件比较好。如下:
在Form上放ExcelApplication1、ExcelWorkbook1、ExcelWorksheet1三个控件。
procedure TForm1.Button3Click(Sender: TObject);
var
idx:integer;
begin
ExcelApplication1.Connect;
ExcelApplication1.Visible[0]:=True;
ExcelApplication1.Workbooks.Add('C:/Program Files/Microsoft Office/Templates/XEKFBB.xlt',0);
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);
ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Sheets[1] as _WorkSheet);
ADOQuery1.First;
idx:=7;
while not ADOQuery1.Eofdo
begin
ExcelWorksheet1.Cells.Item[idx,1]:=ADOQuery1.FieldValues['unitcode'];
ExcelWorksheet1.Cells.Item[idx,2]:=ADOQuery1.FieldValues['itemcode'];
ExcelWorksheet1.Cells.Item[idx,3]:=ADOQuery1.FieldValues['itemname'];
ExcelWorksheet1.Cells.Item[idx,4]:=ADOQuery1.FieldValues['speci'];
ExcelWorksheet1.Cells.Item[idx,5]:=ADOQuery1.FieldValues['qty'];
ExcelWorksheet1.Cells.Item[idx,6]:=ADOQuery1.FieldValues['qtyunit'];
ExcelWorksheet1.Cells.Item[idx,7]:=ADOQuery1.FieldValues['rprice'];
ExcelWorksheet1.Cells.Item[idx,8]:=ADOQuery1.FieldValues['minstock'];
ExcelWorksheet1.Cells.Item[idx,9]:=ADOQuery1.FieldValues['unpaid'];
ADOQuery1.Next;
idx:=idx+1;
end;
ExcelWorksheet1.Cells.Item[idx,1]:='合计:';
ExcelWorksheet1.Cells.Item[idx,5]:='=SUM(E7:E'+IntToStr(idx-1)+')';
end;
关闭时用
ExcelApplication1.Disconnect;
ExcelApplication1.Quit;