请看下面的代码:
unit UseExcelExample;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComObj, StdCtrls, OleServer, Excel97;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
ExcelApplication,ExcelWorkSheet,SheetColumn:Variant;
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
ExcelApplication:=CreateOleObject('Excel.Application');
//装了Excel之后注册表中就有Excel.Application项,在HKEY_CLASSES_ROOT下
ExcelApplication.Visible:=true;
ExcelApplication.caption:='Excel 标题';
ExcelApplication.workbooks.add(xlWorksheet);//加入一个WorkBook
//若add后面不加参数,则缺省生成含有3个WorkSheet 的WorkBook
//add后面加参数xlWorksheet,则生成含有1个WorkSheet 的WorkBook (=1好象也有同样的效果)
ExcelApplication.workbooks[1].sheets.add;//加入一个WorkSheet
//加入n个WorkSheet:ExcelApplication.workbooks[1].sheets.add(,,n,);
ExcelWorkSheet:=ExcelApplication.workbooks[1].sheets[1];
ExcelWorkSheet.name:='name';
//改变列属性
SheetColumn:=ExcelWorkSheet.Columns[1];
SheetColumn.ColumnWidth:=20;
SheetColumn.Font.Color:=clBlue;
SheetColumn.Font.Name:='宋体';
SheetColumn.Font.Size:=16;
SheetColumn.Font.Bold:=true;//粗体
SheetColumn.Font.Italic:=true;
SheetColumn.Font.UnderLine:=true;
//单元格赋值
ExcelWorkSheet.cells[1,1]:='s222';//写一个字符串
ExcelWorkSheet.cells[2,1]:=now;//写一个时间值
ExcelWorkSheet.cells[2,3]:=12345;//写一个整数
ExcelWorkSheet.cells[3,3]:=111.432;//写一个浮点数
//最好都转换成字符串,要不然excel可能会自动给你加一些¥之类的符号
ExcelWorkSheet.cells[3,4]:='=Sum(c2,c3)';//写一个公式
//改变单元格属性
ExcelWorkSheet.cells[2,3].Font.Color:=clRed;
ExcelWorkSheet.Range['a1:e6'].Borders.LineStyle:=xlContinuous;//画格
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//关闭Excel
if not VarIsEmpty(ExcelApplication) then
begin
ExcelApplication.DisplayAlerts:=false;//Excel关闭前不进行保存提示
ExcelApplication.Quit;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//访问WorkSheet里的数据
ShowMessage(ExcelWorkSheet.cells.item[2,1]);
end;
end.