type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure setEclStyle;
procedure drawImg;
function getColChar(col: Integer): string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
eclApp: Variant;
imgFile: string;
const
rowStart = 6;
colStart = 3;
//生成99乘法表
procedure TForm1.Button1Click(Sender: TObject);
var
i,j: Integer;
row,col: Integer;
begin
try
//创建OLE对象Excel Application与 WorkBook
eclApp:= CreateOleObject('Excel.Application');
eclApp.workBooks.Add;
except
messagebox(handle,'您的机器里可能未安装Microsoft Excel或异常','无法生成',MB_OK or MB_ICONWARNING);
Exit;
end;
eclApp.visible:= True;
Hide; //生成过程将程序隐藏
try
for i:= 1 to 9 do
begin
eclApp.Cells(rowStart, colStart + i):= i;
eclApp.Cells(rowStart + i, colStart):= i;
for j:= 1 to 9 do
begin
row:= rowStart + i;
col:= colStart + j;
eclApp.Cells(row, col):= i * j;
//设置字体,底框颜色 颜色值为 $00BBGGRR
if i < j then
begin
eclApp.Cells.item[row,col].Font.Color:= $00FF0000;
eclApp.Cells.item[row,col].Interior.Pattern:= 1;
eclApp.cells.item[row,col].Interior.ColorIndex:= 12;
end
else if i > j then
begin
eclApp.Cells.item[row,col].Font.Color:= $0000FF00;
eclApp.Cells.item[row,col].Interior.Pattern:= 1;
eclApp.cells.item[row,col].Interior.ColorIndex:= 9;
end
else begin
eclApp.Cells.item[row,col].Font.Color:= $000000FF;
eclApp.Cells.item[row,col].Interior.Pattern:= 1;
eclApp.cells.item[row,col].Interior.ColorIndex:= 6;
end;
end;
end;
SetEclStyle;
//设置纸线为横向
eclApp.ActiveSheet.PageSetup.Orientation:= 2;
finally
Show;
end;
Application.BringToFront; //将应用程序提前
messagebox(handle,'生成完毕,您可以再进行编辑并存盘','生成成功',MB_OK or MB_ICONINFORMATION);
end;
//程序启动时,创建一张图片,用来插入到生成的Excel表格中
procedure TForm1.FormCreate(Sender: TObject);
var
d: Word;
buf: array[0..255] of char;
begin
d:= GetTempPath(sizeof(buf),buf);
if d > 0 then
begin
imgFile:= buf + 'imgTL.jpg';
drawImg; //调用自定义过程,绘制图形并保存到临时目录
//也可以考虑使用剪贴板
end
else messagebox(handle,'无法得到临时目录!\n你可以继续运行程序\n但是生成的Excel表格将没有图例','取临时文件出错',MB_OK or MB_ICONINFORMATION);
end;
//随便画张图
procedure TForm1.drawImg;
var
bitMap: TBitMap;
w,h: Integer;
begin
W:= 268;
H:= 50;
bitMap:= TBitMap.Create;
try
bitMap.Width:= W;
bitMap.Height:= H;
with bitMap.Canvas do
begin
Font.Size:= 36;
Font.Name:= '隶书';
//返回列的字符表示符
function TForm1.getColChar(col: Integer): string;
const
Ai = 65; //'A'的ASCII码值
begin
if col > 256 then
begin
//允许的最大列数
raise ERangeError.CreateFmt('列(%d)超出允许的最大列数[256]', [col]);
exit
end;
if col <= 26 then Result:= chr(Ai + col -1) else
Result:= chr(Ai + col div 26 - 1) + chr(Ai + (col - 1) mod 26);
end;