下面我给出我最近做的《自考生成绩报表系统》的原码,我想这一定能满足你的要
求:(动态创建Excel对象,Excel表是事先画好地)
unit UntFrmMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, StdCtrls, Buttons, ExtCtrls, ComCtrls, Grids, DBGrids,
DBCtrls;
type
TFrmMain = class(TForm)
pnlTool: TPanel;
BitBtnPrint: TBitBtn;
BitBtnQuit: TBitBtn;
DSPrint: TDataSource;
DBNavigator: TDBNavigator;
DBGridPrint: TDBGrid;
StatusBar: TStatusBar;
EdtGrade: TEdit;
Label1: TLabel;
EdtYear: TEdit;
Label2: TLabel;
qryPrint: TTable;
EdtPage: TEdit;
procedure BitBtnQuitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BitBtnPrintClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
ThisNo : Integer;
implementation
Uses ComObj;//这一行不可少呦
{$R *.DFM}
procedure TFrmMain.BitBtnQuitClick(Sender: TObject);
begin
if QryPrint.Active then
QryPrint.Close;
Close;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
Qryprint.DatabaseName:=ExtractFileDir(Application.ExeName);
QryPrint.TableName:='DBInfo.DB';
if Qryprint.Active=False then Qryprint.Active:=True;
ThisNo:=0;
end;
procedure TFrmMain.BitBtnPrintClick(Sender: TObject);
Var
I,J:Integer;
QryPrintView:TQuery;
ExcelVar:Variant;
cellposition:string;
Const
SQLStr='SELECT ID, Name, Sex, Political, Birthday, Post, FinalRec, Code1, Code2, Code3, Code4, Remark '+
'FROM "DBInfo.db" Dbinfo';
HRang:array[1..14] of string=('A','B','C','D','E','F','G','H','I','J','K','L','M','N');
begin
QryPrintView := TQuery.Create(Self);
try
QryprintView.DataBaseName:=ExtractFileDir(Application.ExeName);
QryprintView.Close;
QryprintView.SQL.Clear;
QryprintView.SQL.Add(Sqlstr);
QryprintView.Open;
QryPrintView.First;
QryprintView.MoveBy(ThisNo);
if QryPrintView.Eof then Exit;
ExcelVar:=CreateOleObject('Excel.Application');
ExcelVar.WorkBooks.Open(ExtractFilePath(ParamStr(0))+'StuRegister.xls');//事先画好的Excel表
ExcelVar.range['A1'].value:=EdtGrade.Text;
ExcelVar.range['C1'].value:=EdtYear.Text;
for i:=5 to 24 do
begin
for j:=1 to QryprintView.fieldcount do
begin
cellposition:=hrang[j]+inttostr(i);
ExcelVar.range[cellposition].value:=QryprintView.fields[j-1].asstring;
end;
if Not QryPrintView.Eof then
QryprintView.next
Else
Begin
ShowMessage('打印数据输出完毕!!!');
Break;
End;
end;
finally
QryPrintView.Free;
end;
ExcelVar.application.Visible:=True;
ExcelVar.activesheet.printpreview;
ThisNo:=ThisNo+20;
EdtPage.Text:='第'+IntToStr(Round(ThisNo/20)+1)+'页';
end;
end.