Excel文件 ( 积分: 100 )

  • 主题发起人 主题发起人 子瑜
  • 开始时间 开始时间

子瑜

Unregistered / Unconfirmed
GUEST, unregistred user!
我在Delphi7.0中用控件操作Excel文件。
如何得到某个工作表中的某行或某列的数据?
并能统计有多少行或多少列?
类似于实现这样的:
For i:=0 to AdoDataSet.RecordCount-1 do
begin
SomeFieldRowValue:=AdoDataSet.Field[1].value;
end;
 
我在Delphi7.0中用控件操作Excel文件。
如何得到某个工作表中的某行或某列的数据?
并能统计有多少行或多少列?
类似于实现这样的:
For i:=0 to AdoDataSet.RecordCount-1 do
begin
SomeFieldRowValue:=AdoDataSet.Field[1].value;
end;
 
这个我也不懂
 
excel控制的资料1:
unit Excels;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs,Dbtables;
type
TEPExcel=class
private
VExcel:variant;{Excel对象变量}
//FileName:string;{文件名}
public
constructor Create(FName:string);
procedure SetCells(CPosition:string;CValue:Variant;FontSize:integer);
procedure SetRange(rv:string;sx,ex,sy,ey,size:integer);
procedure Vsingle(var vquery:tquery;strqury,cc:string;fz:integer);
procedure Setvquary(var equery:Tquery;xs,ys,fs:integer);
procedure Cellmerge(cs,ce,ns,ne,fontsize:integer);
procedure Printpreview();
procedure Print();
procedure Save();
procedure Protect(password:string);
procedure WSCopy;
procedure PreviewBooks;
procedure Unprotect(pw:string);
procedure Unprotectworkbook(pwd:string);
end;

implementation
uses Comobj;

{创建一个Excel对象变量}
Constructor TEPExcel.Create(FName:string);
begin
VExcel:=CreateOleObject('Excel.Application');
VExcel.WorkBooks.Open(FName);
end;

{设置一个单元格属性}
procedure TEPExcel.SetCells(CPosition:string;CValue:Variant;FontSize:integer);
begin
VExcel.Range[CPosition].Font.Size:=FontSize;
VExcel.Range[CPosition].Font.Bold:=True;
VExcel.Range[CPosition].Value:=CValue;
end;

{设置区域属性}
procedure TEPExcel.SetRange(rv:string;sx,ex,sy,ey,size:integer);
const
{Excel的列标志号}
RowNo:array[1..26] of string=
('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U','V','W','X','Y','Z');
var
X:Integer;
Y:Integer;
CP:string;{单元格位置}
begin
for Y:=sy to ey do
begin
for X:=sx to ex do
begin
CP:=RowNo[X]+IntToStr(Y);
VExcel.Range[CP].Font.Bold:=True;
VExcel.Range[CP].Font.Size:=Size;
VExcel.Range[CP].Value:=rv;
end
end;
end;

procedure TEPExcel.setvquary(var equery:Tquery;xs,ys,fs:integer);
const
crs:array[1..26] of string=('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var
rangs:string;
i:integer;
j:integer;

begin

//equery.DatabaseName:=dabname;
//equery.TableName:=tabname;
equery.first;
for j:=ys to equery.recordcount-1+ys do
begin
for i:=xs to equery.fieldcount-1+xs do
begin
rangs:=crs+inttostr(j);
VExcel.range[rangs].font.bold:=true;
VExcel.range[rangs].font.size:=fs;
VExcel.range[rangs].value:=equery.fields[i-xs].asstring;
end;
equery.next;
end;
equery.Destroy;
end;

{合并单元格}
procedure TEPExcel.CellMerge(cs,ce,ns,ne,fontsize:integer);
const
cn:array[1..26] of string=('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var
scell:string;
begin
scell:=cn[cs]+inttostr(ns)+':'+cn[ce]+inttostr(ne);
VExcel.application.DisplayAlerts:=False;
VExcel.range[scell].merge;
VExcel.range[scell].font.size:=fontsize;
VExcel.range[scell].font.bold:=true;
VExcel.range[scell].WrapText:=True;
VExcel.application.DisplayAlerts:=true;
end;

{打印}
procedure TEPExcel.print();
begin
VExcel.range['b5'].activate;
VExcel.application.visible:=true;
VExcel.Worksheets['Sheet1'].PageSetup.Orientation:=2;
VExcel.Worksheets['Sheet1'].printout;
end;

{打印预览}
procedure TEPExcel.printpreview();
begin
VExcel.range['b5'].activate;
VExcel.application.visible:=true;
VExcel.Worksheets['Sheet1'].PageSetup.Orientation:=2;
VExcel.Worksheets['Sheet1'].printpreview;
end;


{存盘}
procedure TEPExcel.save();
begin
VExcel.ActiveWorkbook.Save
end;

{表保护}
procedure TEPExcel.protect(password:string);
begin
VExcel.worksheets['sheet1'].protect(password,true,true,true);
end;

procedure TEPExcel.Vsingle(var vquery:tquery;strqury,cc:string;fz:integer);
begin
vquery.close;
vquery.SQL.Clear;
vquery.SQL.add(strqury);
vquery.open;
VExcel.range[cc].value:=vquery.fields[0].asstring;
end;

procedure TEPExcel.WSCopy;
begin
VExcel.WorkSheets['Sheet1'].Copy(After:=VExcel.WorkSheets[VExcel.WorkSheets.Count]);
VExcel.WorkSheets[VExcel.Worksheets.Count].Protect('aa',true,true,true);
VExcel.workSheets['Sheet1'].Activate;
end;

procedure TEPExcel.PreviewBooks;
begin
VExcel.Application.Visible:=True;
VExcel.Application.ActiveWorkBook.PrintOut(Copies:=1, Preview:=True, Collate:=True );
end;

procedure TEPExcel.UnProtect(pw:string);
var
I:Integer;
begin
for I:=1 to VExcel.WorkSheets.Count do
begin
VExcel.WorkSheets.Select;
VExcel.ActiveSheet.UnProtect(pw);
end;
end;

{解除单元格保护}
procedure TEPExcel.UnProtectworkbook(pwd:string);
begin
VExcel.activeworkbook.unprotect(pwd);
end;

end.


资料2:
unit U_myexcel;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OleServer, Excel2000, DB, DBTables,ComObj,registry,
Buttons, ExcelXP;

type
TF_myexcel = class(TDataModule)
ExcelApplication1: TExcelApplication;

private

public
{ Public declarations }
end;

var
Fexcel:Variant;
F_myexcel: TF_myexcel;
function GetRegString(RootKey: HKEY
Section, Key, DefaultValue: string):string
// 读取注册表键值
function Openexcel: Boolean
//尝试打开excel
procedure SetCells(CPosition:string;CValue:Variant;FontSize:integer)
{设置一个单元格属性}
procedure SetRange(rv:string;sx,ex,sy,ey,size:integer);{设置区域属性}
procedure setvquary(var equery:Tquery;xs,ys,fs:integer)
//设置数据库
procedure input_totable(var etable:Ttable;xs,xs2,ys,ys2,fs:integer)
//输入table
procedure CellMerge(cs,ce,ns,ne,fontsize:integer)
{合并单元格}
procedure print()
{打印}
procedure printpreview()
{打印预览}
procedure save();{存盘}
procedure protect(password:string)
{表保护}
procedure Vsingle(var vquery:tquery;strqury,cc:string;fz:integer)
//设置数据库
procedure WSCopy
//表拷贝
procedure PreviewBooks
//预览
procedure UnProtect(pw:string)
//解除保护
procedure UnProtectworkbook(pwd:string)
{解除单元格保护}

implementation
//@@@@@@@@@@@@@@@@@
function GetRegString(RootKey: HKEY
Section, Key, DefaultValue: string):string;
var
MyReg: TRegistry;
begin
Result := DefaultValue;
MyReg := TRegistry.Create;
if MyReg <> nil then
begin
MyReg.RootKey := RootKey;
if MyReg.OpenKeyReadOnly(Section) then
begin
Result :=MyReg.ReadString(Key);
if Result = '' then Result := DefaultValue;
MyReg.CloseKey;
end;
MyReg.Free;
end;
end;
//&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
//****************
function Openexcel: Boolean;
var
Curexcel: string;
roro:boolean;
rororo:boolean;
begin
roro:=true;
rororo:=true;
Curexcel := GetRegString(HKEY_CLASSES_ROOT, '/excel.Application/CurVer', '', '');
if Curexcel = '' then
begin
Application.MessageBox('请先安装 excel 97 或 excel 2000!或 excel XP 或 excel 2003',
PChar('警告'), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end;
if (Curexcel <> 'excel.Application.8') and (Curexcel <> 'excel.Application.9') then
begin
Curexcel := GetRegString(HKEY_CLASSES_ROOT, '/excel.Application.10/CLSID', '', '');
if Curexcel <> '' then Curexcel := 'excel.Application.10';
if Curexcel = '' then
begin
roro:=false;
end;
end;
if (Curexcel <> 'excel.Application.8') and (Curexcel <> 'excel.Application.9') and (Curexcel <> 'excel.Application.10') then
begin
Curexcel := GetRegString(HKEY_CLASSES_ROOT, '/excel.Application.11/CLSID', '', '');
if Curexcel <> '' then Curexcel := 'excel.Application.11';
if Curexcel = '' then
begin
rororo:=false ;
end;
end;
if (roro=false) and (rororo=false) then
begin
Application.MessageBox('无法运行 excel 97 或 excel 2000,' + #13#10
+ '请检查 excel 97 或 excel 2000 是否已经正确安装。',
PChar('警告!'), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end;
try
Fexcel:= CreateOleObject(Curexcel);
if VarIsEmpty(Fexcel) then
begin
Application.MessageBox('无法运行 excel 97 或 excel 2000,' + #13#10
+ '请检查 excel 97 或 excel 2000 是否已经正确安装。',
PChar('警告!'), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end

except
Application.MessageBox('无法运行 excel 97 或 excel 2000,' + #13#10
+ '请检查 excel 97 或 excel 2000 是否已经正确安装。',
PChar('警告!'), MB_OK + MB_ICONSTOP);
Result := False;
Exit;
end;
try
begin
Fexcel.DisplayAlerts := False;

Fexcel.workbooks.Open(ExtractFilePath(Application.EXEName)+'/mdb/my.xls');
Fexcel.caption:='文件管理系统(测试版)';
Fexcel.Visible := True;
Result := True;
end;
except
Application.MessageBox('分析失败,',
PChar('警告3!'), MB_OK + MB_ICONSTOP);
Result := False;
end;
{
Fexcel.Visible := True
// 1) 显示当前窗口:
Fexcel.Caption := '应用程序调用 Microsoft Excel'
//2) 更改 Excel 标题栏:
Fexcel.WorkBooks.Add
//3) 添加新工作簿:
Fexcel.WorkBooks.Open( 'C:/Excel/Demo.xls' )
//4) 打开已存在的工作簿:
Fexcel.WorkSheets[2].Activate
//5) 设置第2个工作表为活动工作表:
Fexcel.WorksSheets[ 'Sheet2' ].Activate
//或
Fexcel.Cells[1,4].Value := '第一行第四列'
//6) 给单元格赋值:
Fexcel.ActiveSheet.Columns[1].ColumnsWidth := 5
//7) 设置指定列的宽度(单位:字符个数),以第一列为例:
Fexcel.ActiveSheet.Rows[2].RowHeight := 1/0.035
// 1厘米 //8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
Fexcel.WorkSheets[1].Rows[8].PageBreak := 1
//9) 在第8行之前插入分页符:
Fexcel.ActiveSheet.Columns[4].PageBreak := 0
//10) 在第8列之前删除分页符:
Fexcel.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3
//11) 指定边框线宽度://1-左 2-右 3-顶 4-底 5-斜( / ) 6-斜( / )
Fexcel.ActiveSheet.Cells[1,4].ClearContents
//12) 清除第一行第四列单元格公式:
Fexcel.ActiveSheet.Rows[1].Font.Name := '隶书'
//13) 设置第一行字体属性:
Fexcel.ActiveSheet.Rows[1].Font.Color := clBlue;
Fexcel.ActiveSheet.Rows[1].Font.Bold := True;
Fexcel.ActiveSheet.Rows[1].Font.UnderLine := True;
//14) 进行页面设置:
Fexcel.ActiveSheet.PageSetup.CenterHeader := '报表演示'
//a.页眉:
Fexcel.ActiveSheet.PageSetup.CenterFooter := '第&amp;P页'
//b.页脚:
Fexcel.ActiveSheet.PageSetup.HeaderMargin := 2/0.035
//c.页眉到顶端边距2cm:
Fexcel.ActiveSheet.PageSetup.HeaderMargin := 3/0.035
//d.页脚到底端边距3cm:
Fexcel.ActiveSheet.PageSetup.TopMargin := 2/0.035
//e.顶边距2cm:
Fexcel.ActiveSheet.PageSetup.BottomMargin := 2/0.035
//f.底边距2cm:
Fexcel.ActiveSheet.PageSetup.LeftMargin := 2/0.035
//g.左边距2cm:
Fexcel.ActiveSheet.PageSetup.RightMargin := 2/0.035
//h.右边距2cm:
Fexcel.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035
//i.页面水平居中:
Fexcel.ActiveSheet.PageSetup.CenterVertically := 2/0.035
//j.页面垂直居中:
Fexcel.ActiveSheet.PageSetup.PrintGridLines := True
//k.打印单元格网线:
//15) 拷贝操作:
Fexcel.ActiveSheet.Used.Range.Copy
//a.拷贝整个工作表:
Fexcel.ActiveSheet.Range[ 'A1:E2' ].Copy
//b.拷贝指定区域: 好像不好使
Fexcel.ActiveSheet.Range[ 'A1:E2' ].PasteSpecial
//c.从A1位置开始粘贴:
Fexcel.ActiveSheet.Range.PasteSpecial
//d.从文件尾部开始粘贴:
Fexcel.ActiveSheet.Rows[2].Insert
//16) 插入一行或一列:
Fexcel.ActiveSheet.Columns[1].Insert
//16) 插入一行或一列
Fexcel.ActiveSheet.Rows[2].Delete
//17) 删除一行或一列:
Fexcel.ActiveSheet.Columns[1].Delete
//17) 删除一行或一列:
Fexcel.ActiveSheet.PrintPreview
//18) 打印预览工作表:
Fexcel.ActiveSheet.PrintOut
//19) 打印输出工作表:
if not Fexcel.ActiveWorkBook.Saved then //20) 工作表保存:
Fexcel.ActiveSheet.PrintPreview;
Fexcel.SaveAs( 'C:/Excel/Demo1.xls' )
//21) 工作表另存为:
Fexcel.ActiveWorkBook.Saved := True
//22) 放弃存盘:
//23) 关闭工作簿:
Fexcel.WorkBooks.Close;
//24) 退出 Excel:
//Fexcel.Quit
}



end;
//@@@@@@@@@@@@@@@
{设置一个单元格属性}
procedure SetCells(CPosition:string;CValue:Variant;FontSize:integer);
begin
Fexcel.Range[CPosition].Font.Size:=FontSize;
Fexcel.Range[CPosition].Font.Bold:=True;
Fexcel.Range[CPosition].Value:=CValue;
end;

{设置区域属性}
procedure SetRange(rv:string;sx,ex,sy,ey,size:integer);
const
{Excel的列标志号}
RowNo:array[1..26] of string=
('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U','V','W','X','Y','Z');
var
X:Integer;
Y:Integer;
CP:string;{单元格位置}
begin
for Y:=sy to ey do
begin
for X:=sx to ex do
begin
CP:=RowNo[X]+IntToStr(Y);
Fexcel.Range[CP].Font.Bold:=True;
Fexcel.Range[CP].Font.Size:=Size;
Fexcel.Range[CP].Value:=rv;
end
end;
end;

procedure setvquary(var equery:Tquery;xs,ys,fs:integer)
//xs:从excel的xs列开始,ys:从cecel的ys行开始,fs:字体
const
crs:array[1..26] of string=('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var
rangs:string;
i:integer;
j:integer;

begin
//equery.DatabaseName:=''
使用时应该有。
//equery.TableName:='';
equery.first;
for j:=ys to equery.recordcount-1+ys do
begin
for i:=xs to equery.fieldcount-1+xs do
begin
rangs:=crs+inttostr(j);
Fexcel.range[rangs].font.bold:=true;
Fexcel.range[rangs].font.size:=fs;
Fexcel.range[rangs].value:=equery.fields[i-xs].asstring;
end;
equery.next;
end;
equery.Destroy;
end;

{合并单元格}
procedure CellMerge(cs,ce,ns,ne,fontsize:integer)
//cs,ce:列开始与结束点,ns,ne:行开始与结束点.fontsize在excel里默认的是12;
const
cn:array[1..26] of string=('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var
scell:string;
begin
scell:=cn[cs]+inttostr(ns)+':'+cn[ce]+inttostr(ne);
Fexcel.application.DisplayAlerts:=False;
Fexcel.range[scell].merge;
Fexcel.range[scell].font.size:=fontsize;
Fexcel.range[scell].font.bold:=true;
Fexcel.range[scell].WrapText:=True;
Fexcel.application.DisplayAlerts:=true;
end;

{打印}
procedure print();
begin
Fexcel.range['b5'].activate;
Fexcel.application.visible:=true;
Fexcel.Worksheets['Sheet1'].PageSetup.Orientation:=2;
Fexcel.Worksheets['Sheet1'].printout;
end;

{打印预览}
procedure printpreview();
begin
Fexcel.range['b5'].activate;
Fexcel.application.visible:=true;
Fexcel.Worksheets['Sheet1'].PageSetup.Orientation:=2;
Fexcel.Worksheets['Sheet1'].printpreview;
end;


{存盘}
procedure save();
begin
Fexcel.ActiveWorkbook.Save
end;

{表保护}
procedure protect(password:string);
begin
Fexcel.worksheets['sheet1'].protect(password,true,true,true);
end;

procedure Vsingle(var vquery:tquery;strqury,cc:string;fz:integer)
//cc:表示单元格,如A5,///等..fz:字体
begin
vquery.close;
vquery.SQL.Clear;
vquery.SQL.add(strqury);
vquery.open;
Fexcel.range[cc].value:=vquery.fields[0].asstring;
end;

procedure WSCopy;
begin
Fexcel.WorkSheets['Sheet1'].Copy(After:=Fexcel.WorkSheets[Fexcel.WorkSheets.Count]);
Fexcel.WorkSheets[Fexcel.Worksheets.Count].Protect('aa',true,true,true);
Fexcel.workSheets['Sheet1'].Activate;
end;

procedure PreviewBooks;
begin
Fexcel.Application.Visible:=True;
Fexcel.Application.ActiveWorkBook.PrintOut(Copies:=1, Preview:=True, Collate:=True );
end;

procedure UnProtect(pw:string);
var
I:Integer;
begin
for I:=1 to Fexcel.WorkSheets.Count do
begin
Fexcel.WorkSheets.Select;
Fexcel.ActiveSheet.UnProtect(pw);
end;
end;

{解除单元格保护}
procedure UnProtectworkbook(pwd:string);
begin
Fexcel.activeworkbook.unprotect(pwd);
end;
procedure input_totable(var etable: Ttable
xs,xs2, ys,ys2, fs: integer)
//从xs列,ys行开始的xs2+1行和ys2+1列均导入数据库
const
crs:array[1..26] of string=('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var
rangs:string;
i,ii:integer;
j,jj:integer;
begin
//equery.DatabaseName:=''
使用时应该有。
//equery.TableName:='';
etable.first;
for j:=ys to ys2+ys do
begin
etable.Append;
for i:=xs to xs2+xs do
begin
rangs:=crs+inttostr(j);
etable.fields[i-xs].asstring:=Fexcel.range[rangs].value;
end;
etable.next;
end;
// etable.Destroy;
end;
//@@@@@@@@@@@@@@@@
{$R *.dfm}

{ TF_myexcel }




end.


具体代码就不写了。相信您看了这些对excel操作也差不多了。
我想如果用以上代码实现的话只能在一定范围内对表格判断是否为空了吧?
哪位还有好的办法吗?学习学习。。呵呵。。。
 
ADOConnection1.GetTableNames(ComboBox1.Items ,false)

for i:=0 to ADOQuery1.FieldCount-1 do
comboBox2.Items.Add(ADOQuery1.Fields.FieldName);
 
搜一下DFW离线包吧.很简单的.
 
Delphi控制Excel2000心得- -



类 别:COM &amp
ActiveX
(一) 使用动态创建的方法
首先创建 Excel 对象,使用ComObj:
var ExcelApp: Variant

ExcelApp := CreateOleObject( 'Excel.Application' )

1) 显示当前窗口:
ExcelApp.Visible := True

2) 更改 Excel 标题栏:
ExcelApp.Caption := '应用程序调用 Microsoft Excel'

3) 添加新工作簿:
ExcelApp.WorkBooks.Add

4) 打开已存在的工作簿:
ExcelApp.WorkBooks.Open( 'C:/Excel/Demo.xls' )

5) 设置第2个工作表为活动工作表:
ExcelApp.WorkSheets[2].Activate


ExcelApp.WorksSheets[ 'Sheet2' ].Activate

6) 给单元格赋值:
ExcelApp.Cells[1,4].Value := '第一行第四列'

7) 设置指定列的宽度(单位:字符个数),以第一列为例:
ExcelApp.ActiveSheet.Columns[1].ColumnsWidth := 5

8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
ExcelApp.ActiveSheet.Rows[2].RowHeight := 1/0.035
// 1厘米
9) 在第8行之前插入分页符:
ExcelApp.WorkSheets[1].Rows[8].PageBreak := 1

10) 在第8列之前删除分页符:
ExcelApp.ActiveSheet.Columns[4].PageBreak := 0

11) 指定边框线宽度:
ExcelApp.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3

1-左 2-右 3-顶 4-底 5-斜( / ) 6-斜( / )
12) 清除第一行第四列单元格公式:
ExcelApp.ActiveSheet.Cells[1,4].ClearContents

13) 设置第一行字体属性:
ExcelApp.ActiveSheet.Rows[1].Font.Name := '隶书'

ExcelApp.ActiveSheet.Rows[1].Font.Color := clBlue

ExcelApp.ActiveSheet.Rows[1].Font.Bold := True

ExcelApp.ActiveSheet.Rows[1].Font.UnderLine := True

14) 进行页面设置:
a.页眉:
ExcelApp.ActiveSheet.PageSetup.CenterHeader := '报表演示'

b.页脚:
ExcelApp.ActiveSheet.PageSetup.CenterFooter := '第&amp;P页'

c.页眉到顶端边距2cm:
ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 2/0.035

d.页脚到底端边距3cm:
ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 3/0.035

e.顶边距2cm:
ExcelApp.ActiveSheet.PageSetup.TopMargin := 2/0.035

f.底边距2cm:
ExcelApp.ActiveSheet.PageSetup.BottomMargin := 2/0.035

g.左边距2cm:
ExcelApp.ActiveSheet.PageSetup.LeftMargin := 2/0.035

h.右边距2cm:
ExcelApp.ActiveSheet.PageSetup.RightMargin := 2/0.035

i.页面水平居中:
ExcelApp.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035

j.页面垂直居中:
ExcelApp.ActiveSheet.PageSetup.CenterVertically := 2/0.035

k.打印单元格网线:
ExcelApp.ActiveSheet.PageSetup.PrintGridLines := True

15) 拷贝操作:
a.拷贝整个工作表:
ExcelApp.ActiveSheet.Used.Range.Copy

b.拷贝指定区域:
ExcelApp.ActiveSheet.Range[ 'A1:E2' ].Copy

c.从A1位置开始粘贴:
ExcelApp.ActiveSheet.Range.[ 'A1' ].PasteSpecial

d.从文件尾部开始粘贴:
ExcelApp.ActiveSheet.Range.PasteSpecial

16) 插入一行或一列:
a. ExcelApp.ActiveSheet.Rows[2].Insert

b. ExcelApp.ActiveSheet.Columns[1].Insert

17) 删除一行或一列:
a. ExcelApp.ActiveSheet.Rows[2].Delete

b. ExcelApp.ActiveSheet.Columns[1].Delete

18) 打印预览工作表:
ExcelApp.ActiveSheet.PrintPreview

19) 打印输出工作表:
ExcelApp.ActiveSheet.PrintOut

20) 工作表保存:
if not ExcelApp.ActiveWorkBook.Saved then
ExcelApp.ActiveSheet.PrintPreview

21) 工作表另存为:
ExcelApp.SaveAs( 'C:/Excel/Demo1.xls' )

22) 放弃存盘:
ExcelApp.ActiveWorkBook.Saved := True

23) 关闭工作簿:
ExcelApp.WorkBooks.Close

24) 退出 Excel:
ExcelApp.Quit


(二) 使用Delphi 控件方法
在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
1) 打开Excel
ExcelApplication1.Connect

2) 显示当前窗口:
ExcelApplication1.Visible[0]:=True

3) 更改 Excel 标题栏:
ExcelApplication1.Caption := '应用程序调用 Microsoft Excel'

4) 添加新工作簿:
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0))

5) 添加新工作表:
var Temp_Worksheet: _WorkSheet

begin
Temp_Worksheet:=ExcelWorkbook1.
WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet

ExcelWorkSheet1.ConnectTo(Temp_WorkSheet)

End

6) 打开已存在的工作簿:
ExcelApplication1.Workbooks.Open (c:/a.xls
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)
7) 设置第2个工作表为活动工作表:
ExcelApplication1.WorkSheets[2].Activate

ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate

8) 给单元格赋值:
ExcelApplication1.Cells[1,4].Value := '第一行第四列'

9) 设置指定列的宽度(单位:字符个数),以第一列为例:
ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5

10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035
// 1厘米
11) 在第8行之前插入分页符:
ExcelApplication1.WorkSheets[1].Rows[8].PageBreak := 1

12) 在第8列之前删除分页符:
ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0

13) 指定边框线宽度:
ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3

1-左 2-右 3-顶 4-底 5-斜( / ) 6-斜( / )
14) 清除第一行第四列单元格公式:
ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents

15) 设置第一行字体属性:
ExcelApplication1.ActiveSheet.Rows[1].Font.Name := '隶书'

ExcelApplication1.ActiveSheet.Rows[1].Font.Color := clBlue

ExcelApplication1.ActiveSheet.Rows[1].Font.Bold := True

ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True

16) 进行页面设置:
a.页眉:
ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示'

b.页脚:
ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&amp;P页'

c.页眉到顶端边距2cm:
ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035

d.页脚到底端边距3cm:
ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035

e.顶边距2cm:
ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035

f.底边距2cm:
ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035

g.左边距2cm:
ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035

h.右边距2cm:
ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035

i.页面水平居中:
ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035

j.页面垂直居中:
ExcelApplication1.ActiveSheet.PageSetup.CenterVertically := 2/0.035

k.打印单元格网线:
ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True

17) 拷贝操作:
a.拷贝整个工作表:
ExcelApplication1.ActiveSheet.Used.Range.Copy

b.拷贝指定区域:
ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy

c.从A1位置开始粘贴:
ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial

d.从文件尾部开始粘贴:
ExcelApplication1.ActiveSheet.Range.PasteSpecial

18) 插入一行或一列:
a. ExcelApplication1.ActiveSheet.Rows[2].Insert

b. ExcelApplication1.ActiveSheet.Columns[1].Insert

19) 删除一行或一列:
a. ExcelApplication1.ActiveSheet.Rows[2].Delete

b. ExcelApplication1.ActiveSheet.Columns[1].Delete

20) 打印预览工作表:
ExcelApplication1.ActiveSheet.PrintPreview

21) 打印输出工作表:
ExcelApplication1.ActiveSheet.PrintOut

22) 工作表保存:
if not ExcelApplication1.ActiveWorkBook.Saved then
ExcelApplication1.ActiveSheet.PrintPreview

23) 工作表另存为:
ExcelApplication1.SaveAs( 'C:/Excel/Demo1.xls' )

24) 放弃存盘:
ExcelApplication1.ActiveWorkBook.Saved := True

25) 关闭工作簿:
ExcelApplication1.WorkBooks.Close

26) 退出 Excel:
ExcelApplication1.Quit

ExcelApplication1.Disconnect

(三) 使用Delphi 控制Excle二维图
在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet
var asheet1,achart, range:variant

1)选择当第一个工作薄第一个工作表
asheet1:=ExcelApplication1.Workbooks[1].Worksheets[1]

2)增加一个二维图
achart:=asheet1.chartobjects.add(100,100,200,200)

3)选择二维图的形态
achart.chart.charttype:=4

4)给二维图赋值
series:=achart.chart.seriescollection

range:=sheet1!r2c3:r3c9

series.add(range,true)

5)加上二维图的标题
achart.Chart.HasTitle:=True

achart.Chart.ChartTitle.Characters.Text:=' Excle二维图'
6)改变二维图的标题字体大小
achart.Chart.ChartTitle.Font.size:=6

7)给二维图加下标说明
achart.Chart.Axes(xlCategory, xlPrimary).HasTitle := True

achart.Chart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text := '下标说明'

8)给二维图加左标说明
achart.Chart.Axes(xlValue, xlPrimary).HasTitle := True

achart.Chart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text := '左标说明'

9)给二维图加右标说明
achart.Chart.Axes(xlValue, xlSecondary).HasTitle := True

achart.Chart.Axes(xlValue, xlSecondary).AxisTitle.Characters.Text := '右标说明'

10)改变二维图的显示区大小
achart.Chart.PlotArea.Left := 5

achart.Chart.PlotArea.Width := 223

achart.Chart.PlotArea.Height := 108

11)给二维图坐标轴加上说明
achart.chart.seriescollection[1].NAME:='坐标轴说明'


unit Unit1


interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
ComObj


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.FormDestroy(Sender: TObject)

begin
//关闭eclApp
//若不进行这一步,在任务管理器中会驻留Excel进程
//但可以不必关闭Excel (eclApp.Quit),这样,操作员可以继续编辑或打印表格
eclApp:= Unassigned

end


//设置表格的显示样式
procedure TForm1.setEclStyle

var
Sheet, Range:Variant

s: string

rct: TRect

begin

Sheet:= eclApp.WorkBooks[1].WorkSheets[1]


s:= Format('%s%d:%s%d',[getColChar(colStart),
rowStart,
getColChar(colStart + 9),
rowStart + 9])

Range:= Sheet.Range
//得到区域对象

Range.Font.Name:= 'Tahoma'

Range.Font.Bold:= True


//设置区域的外框线型
// 1: Left, 2: Right, 3: Top, 4: bottom
// 5: /, 6: / (斜线)
// 7: Left, 8: Top, 9: bottom, 10: Right (不包括内部单元格)
// 11, 12 , 内部单元格线条 (分别是竖线和横线,12我用了没效果)
Range.Borders[7].LineStyle:= 1

Range.Borders[7].Weight:= 3

Range.Borders[8].LineStyle:= 1

Range.Borders[8].Weight:= 3

Range.Borders[9].LineStyle:= 1

Range.Borders[9].Weight:= 3

Range.Borders[10].LineStyle:= 1

Range.Borders[10].Weight:= 3


Range.Borders[11].LineStyle:= 1

Range.Borders[11].Weight:= 2

Range.Borders[11].ColorIndex:= 2

Range.Borders[12].LineStyle:= 1

Range.Borders[12].Weight:= 2

Range.Borders[12].ColorIndex:= 2


//水平,垂直对齐方式
Range.HorizontalAlignment:= 3

Range.VerticalAlignment:= 2


//单元格行高,列宽
Range.ColumnWidth:= 9

Range.RowHeight:= 18;
 
关于解除单元格保护
procedure UnProtectworkbook(pwd:string);
begin
Fexcel.activeworkbook.unprotect(pwd);
end;
在不知密码情况下,如何解除单元格保护?有知道取得单元格保护密码方法的吗?传上来学习学习。
 
procedure ThrashYou();
var
i,j,k:integer;
Row,column:integer;
WorkShtCount:integer;
begin
try
ExcelApplication1.Connect;
except
MessageDlg('Excel 是否已正确安装',mtError,[mbOk],0);
Abort;
end;
ExcelApplication1.Visible[0]:=True;
ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';
ExcelApplication1.Workbooks.Open('D:/cvsroot/SDHY_/测试数据表.xls',
EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam, EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,0);
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);
Excelworkbook1.Activate;
WorkShtCount:=Excelworkbook1.Worksheets.Count;
for i := 1 to WorkShtCount do // Iterate
begin
ExcelWorkSheet1.ConnectTo(Excelworkbook1.Worksheets as _worksheet);
ExcelWorkSheet1.Activate;
{问题:如何取出某工作表第二列的数据?}
end
// for

end;
 
还是用Ole对象来做吧,扩展性强,delphi的excel控件实在不太好使

具体的属性,去查看VBA吧。。。如果你对VB熟悉就很容易
 
弄的例子都是怎么设置表内容或什么的.我是要得到数据啊,不是设置啊.谁会?救救我啊.
 
8) 给单元格赋值:
ExcelApplication1.Cells[1,4].Value := '第一行第四列'


楼主真是。。。。例子里不是有么
 
呵呵,谢谢,你看错题意了.
不是要给单元格赋值.而是从单元格中取出值,不过我自己已经弄出来了.
如取某单元格的值:
CellsValue:=ExcelWorkSheet1.Cells.Item[Row,col];

但是一下取出某列的数据就不知道了.Java中可以通过GetRows()得到总行数,通过getRow(row)返回某行数据.这样的话对工作表的数据好控制了.可惜Delphi中我不知道怎么去取这些总行数或总列数.某行数据或某列数据.
只能这样去取:
例如一行行地取出第一列的值.
RowCount:=2;
Repeat
CellsValue:=ExcelWorkSheet1.Cells.Item[RowCount,1];//第一列的数据
inc(RowCount);
until Trim(CellsValue)=''
//只好在这遇到空值就退出.因为我不知道行数嘛.

嫌分少我很多的,另外给.
 
str:=ExcelApplication1.Cells[1,4].Value;不就是取值么? 不懂楼主什么想法。。

我一般不用EXCEL控件,我是用OLE对象
var
Excel: OleVariant;
maxrow,i:integer;
begin
Excel := CreateOLEObject('Excel.Application');
maxrow:=Excel.WorkSheets[1].UsedRange.Rows.Count;//取出使用的最大行数
for i:=1 to maxrow do
//要做的事
end;

如果如果用EXCEL控件的话也一样,ExcelWorksheet1.UsedRange.Rows.Count
 
非常感谢。
 
谢谢各位兄弟姐妹们,谢谢!谢谢!
 
后退
顶部