c++Builder操作Excel(2008-10-05 08:36:03)转载▼标签: cexcel杂谈
近期为了给教研室做一个签到的小软件,主要思路是各人上下班后在自己机子上的客户端点上下班,服务器将每个人的上下班时间自动的写到excel表格里去,用到了程序对excel的一些操作,现整理如下:
要在应用程序中控制Excel2000的运行,首先必须在编制自动化客户程序时使其头文件要包含Comobj.hpp和Utilcls.h。
即:#include
#include
C++ Builder开发者把Excel自动化对象的功能包装在下面的四个Ole Object Class函数中,应用人员可以很方便地进行调用。
设置对象属性:Variant OlePropertySet(属性名,参数……);
获得对象属性:void OlePropertyGet(属性名,参数……);
调用对象方法:1) Variant OleFunction(函数名,参数……);
2) void OleProcedure(过程名,参数……);
C++ Builder中使用OLE控制Excel2000,必须掌握Excel2000的自动化对象及Microsoft Word Visual Basic帮助文件中的关于Excel的对象、方法和属性。对象是一个Excel元素,属性是对象的一个特性或操作的一个方面,方法是对象可以进行的动作。
1、Excel中常用的对象是:Application,Workbooks,Worksheets等。
(1) 创建应用对象:如:
Variant ex;
ex=Variant::CreateObject ("Excel.Application");
或者 ex=CreateOleObject ("Excel.Application");
(2) 创建工作簿对象:
Variant wb;
wb=ex.OlePropertyGet("ActiveWorkBook");
(3) 创建工作表对象:
Variant sheet;
sheet=wb.OlePropertyGet("ActiveSheet");
(4) 创建区域对象:
Variant range;
range=sheet.OlePropertyGet("Range","A1:A10");
2、常用的属性操作:
(1)新建EXCEL文件:
(a):新建系统模板的工作簿
ex.OlePropertyGet("workbooks").OleFunction("Add") //默认工作簿
ex.OlePropertyGet("workbooks").OleFunction("Add",1) //单工作表
ex.OlePropertyGet("workbooks").OleFunction("Add",2) //图表
ex.OlePropertyGet("workbooks").OleFunction("Add",3) //宏表
ex.OlePropertyGet("workbooks").OleFunction("Add",4) //国际通用宏表
ex.OlePropertyGet("workbooks").OleFunction("Add",5) //与默认的相同
ex.OlePropertyGet("workbooks").OleFunction("Add",6) //工作簿且只有一个表
(b):新建自己创建的模板的工作簿
ex.OlePropertyGet("workbooks").OleFunction("Add","C:\\WINDOWS\\Profiles\\test2\\Application Data\\Microsoft\\Templates\\result.xlt"); // 后面写上模板的完全路径,注意“\\”
(2)打开工作簿:
ex.OlePropertyGet("workbooks").OleFunction("open","路径名.xls")
(3)保存工作簿:
wb.OleFunction("Save"); //表格保存
wb..OleFunction("SaveAs","文件名"); //表格保存为,文件路径注意用“\\”
(4)退出EXCEL:
ex.OleFunction ("Quit");
(5)设置字体:
(a):设置单元格字体
sheet.OlePropert
yGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Name","隶书");
sheet.OlePropertyGet("Cells",2,3).OlePropertyGet("Font").OlePropertySet("size",28);
(b):设置所选区域字体
range.OlePropertyGet("Cells").OlePropertyGet("Font").OlePropertySet("size",28); range.OlePropertyGet("Cells").OlePropertyGet("Font").OlePropertySet("Color",
RGB(0,0,255));
其中参数的设置:
Font---Name : “隶书” //字体名称
----Size : 12 //字体大小
----Color : RGB(*,*,*) //颜色
-----Underline : true/false //下划线
-----Italic: true/false //斜体
(6)单元格的合并:
(a) range1=sheet.OlePropertyGet("Range", "A1:A2"); //A1和A2单元格合并
(b) AnsiString Str="A"+IntToStr(j)+":"+"C"+IntToStr(j);
range1=sheet.OlePropertyGet("Range",Str); //可以用变量控制单元格合并
range1.OleFunction("Merge" , false);
(7)赋值语句:
(a):指定单元格赋值
sheet.OlePropertyGet("Cells",3,6).OlePropertySet("Value",str);
sheet.OlePropertyGet("Cells",j,1).OlePropertySet("Value","共查到记录:"+IntToStr(j-6));
(b):所选区域单元格赋值
range.OlePropertyGet("Cells").OlePropertySet("Value",10);
(c):所选区域行赋值
range.OlePropertyGet("Rows",1).OlePropertySet("Value",1234);
(d):工作表列赋值
sheet.OlePropertyGet("Columns",1).OlePropertySet("Value",1234);
(8)取值语句:
AnsiString abc=sheet.OlePropertyGet("Cells",120,1).OlePropertyGet("Value");
(9)区域选择:
range.OlePropertyGet("Cells").OleFunction("Select");
(10)窗口属性:
(a)显示属性
ex.OlePropertySet("Windowstate",3); //最大化显示
参数 1---------xlNormal //正常显示
2---------xlMinimized //最小化显示
3---------xlMaximized //最大化显示
(b)状态栏属性
ex.OlePropertySet ("StatusBar","您好,请您稍等。正在查询!");
ex.OlePropertySet ("StatusBar", false); //还原成默认值
(c)标题属性:
ex.OlePropertySet("Caption","查询系统");
=====================================================================
在实际工作中经常用Excel表做数据报表,大多数表格的数据都要从数据库中读取,这样我就用C++Builder做了一个报表程序,方便了很多,现在把它共享给C++Builder爱好者们,就算为丰富C++Builder的文档资料做点事情吧。
首先把Excel报表文件保存到一个指定目录下,最好放在可执行程序的子目录下,作为模板文件。可以把报表标题、表头等设置好。这里是保存在trpt子目录下。
然后建一个report目录,作为报表目标文件夹,存放填好数据的报表,可以由用户直接操作。
首先确定在你的机器中装有Office。这里一Office2000为例。
在C++Builder中新建一个工程,在窗体Form1上面放一个两个按钮SaveButton和ReadButton,分别用来保存数据到Excel表和显示刚刚保存的Excel表。
在SaveButton
按钮的单击事件中把从数据库中取到的数据放入到指定的Excel表中并将改文件拷贝到report目录下。在ReadButto按钮的单击事件中显示report目录下的报表文件,方便用户修改和另外保存。
在Form1.h头文件中定义几个变量:
private:
Variant Ex,Wb,Sheet,ERange,EBorders;
并在文件头中包含如下语句:
#include "Excel_2K_SRVR.h"
#include
在Form1.cpp的文件头中加入
#pragma link "Excel_2K_SRVR"
主要代码如下:
void __fastcall TForm1:: SaveButtonClick(TObject *Sender)
{
try
{
SaveButton->Enabled = false;
ReadButton->Enabled = false;//使两个按钮无效
file://取报表文件CardSend.xls的完整目录名
AnsiString ExcelFileName = GetCurrentDir()+"\\trpt\\table.xls";
if(!FileExists(ExcelFileName))
{
Application->MessageBox("报表模板文件不存在,无法打开!",
"错误",MB_ICONSTOP|MB_OK);
return;
}
file://建立Excel的Ole对象Ex
try
{
Ex = Variant::CreateObject("Excel.Application");
}
catch(...)
{
Application->MessageBox("无法启动Excel","错误",MB_ICONSTOP|MB_OK);
return;
}
file://设置Excel为不可见
Ex.OlePropertySet("Visible",false);
file://打开指定的Excel报表文件。报表文件中最好设定只有一个Sheet。
Ex.OlePropertyGet("WorkBooks").OleProcedure("Open",ExcelFileName.c_str());
Wb = Ex.OlePropertyGet("ActiveWorkBook");
Sheet = Wb.OlePropertyGet("ActiveSheet");//获得当前默认的Sheet
file://清空Excel表,这里是用循环清空到第300行。对于一般的表格已经足够了。
AnsiString strRowTemp;
AnsiString strRange;
int iCols,iRows;//记录列数和行数
/*从第三行开始,到第300行止。一般第一行是表标题,第二行是副标题或者制表日期。*/
for(iRows=3;iRows<300;iRows++)
{ file://假设只有6列。
for (iCols = 1;iCols < 7; iCols++)
{
file://清空行
Sheet.OlePropertyGet("Cells",iRows,iCols).OlePropertySet("Value","");
}
file://去掉表格边框
strRange = "A"+IntToStr(iRows)+":F"+IntToStr(iRows);//获取操作范围
ERange = Sheet.OlePropertyGet("Range",strRange.c_str());
EBorders = ERange.OlePropertyGet("Borders");//获取边框对象
EBorders.OlePropertySet("linestyle",xlNone);
}
AnsiString strPtrDate; file://存放当前日期,作为制表日期
DateSeparator = '-';
ShortDateFormat = "yyyy/m/d";//设置为年/月/日格式
strPtrDate = DateToStr(Date());//取当前日期
AnsiString strYear = strPtrDate.SubString(1,4);
strPtrDate = strPtrDate.SubString(6,strPtrDate.Length()-5);
AnsiString strMonth = strPtrDate.SubString(1,strPtrDate.Pos("-")-1);
AnsiString strDay =
strPtrDate.SubString(strPtrDate.Pos("-")+1,
strPtrDate.Length()-strPtrDate.Pos("-"));
strPtrDate = strYear+"年"+strMonth+"月"+strDay+"日";
AnsiString strData = "报表标题";//报表标题
file://将报表标题置于第一行第一列。在此之前,应将报表文件的标题格
式设定好。
Sheet.OlePropertyGet("Cells",1,1).OlePropertySet("Value",
strData.c_str());
file://将制表日期置于表格第二行的右侧。
Sheet.OlePropertyGet("Cells",2,5).OlePropertySet("Value",
strPtrDate.c_str());
iRows = 3;//在第三行放置表格的列名
Sheet.OlePropertyGet("Cells",iRows,1).OlePropertySet("Value","列名1");
Sheet.OlePropertyGet("Cells",iRows,2).OlePropertySet("Value","列名2");
Sheet.OlePropertyGet("Cells",iRows,3).OlePropertySet("Value","列名3");
Sheet.OlePropertyGet("Cells",iRows,4).OlePropertySet("Value","列名4");
Sheet.OlePropertyGet("Cells",iRows,5).OlePropertySet("Value","列名5");
Sheet.OlePropertyGet("Cells",iRows,6).OlePropertySet("Value","列名6");
file://画表格边框,在A3:F3之间取范围
strRange = "A"+IntToStr(iRows)+":F"+IntToStr(iRows);
ERange = Sheet.OlePropertyGet("Range",strRange.c_str());
EBorders = ERange.OlePropertyGet("Borders");
EBorders.OlePropertySet("linestyle",xlContinuous);
EBorders.OlePropertySet("weight",xlThin);
EBorders.OlePropertySet("colorindex",xlAutomatic);
iRows++;
file://从数据库中取数据(略),假设数据集放入Query1中。
Query1->Open();//打开数据集
file://循环取数
while(!Query1->Eof)
{
file://循环取字段的数据放到Excel表对应的行列中
for(iCols=1;iCols<7;iCols++)
{
strRowTemp = Query1->Fields->Fields[iCols-1]->AsString;
Sheet.OlePropertyGet("Cells",iRows,iCols).OlePropertySet("Value",
strRowTemp.c_str());
}
file://画该行的表格边框
strRange = "A"+IntToStr(iRows)+":F"+IntToStr(iRows);
ERange = Sheet.OlePropertyGet("Range",strRange.c_str());
EBorders = ERange.OlePropertyGet("Borders");
EBorders.OlePropertySet("linestyle",xlContinuous);
EBorders.OlePropertySet("weight",xlThin);
EBorders.OlePropertySet("colorindex",xlAutomatic);
iRows++;
Query1->Next();
}//while结束
Wb.OleProcedure("Save");//保存表格
Wb.OleProcedure("Close");关闭表格
Ex.OleFunction("Quit");退出Excel
file://定义目标文件名
AnsiString DestinationFile =
GetCurrentDir()+"\\report\\table.xls";
file://将刚刚修改的Excel表格文件table.xls拷贝到report目录下
if(!CopyFile(ExcelFileName.c_str(),DestinationFile.c_str(),false))
{
Application->MessageBox("复制文件操作失败,Excel文件可能正在使用中!",
"错误",MB_ICONSTOP|MB_OK);
return;
}
Application->MessageBox("成功完成报表保存!\n可以按\'打开Excel文件\'
按钮进行报表工作","提示",MB_ICONINFORMATION|MB_OK);
SaveButton ->Enabled = true;
ReadButton ->Enabled=true;
}//try结束
catch(...)
{
Application->MessageBox("操作Excel表格失败!",
"错误",MB_ICONSTOP|MB_OK);
Wb.OleProcedure("Close");
Ex.OleFunction("Quit");
SaveButton ->Enabled = true;
ReadButton ->Enabled=false;
}
}
至此,完成报表数据的写入工作。如果要对完成的Excel表进行操作,可以点击"打开Excel表文件按钮"(ReadButton),进行修改,保存,打印等操
作。ReadButton的单击事件如下实现:
void __fastcall TForm1:: ReadButtonClick(TObject *Sender)
{
try
{
file://指定report目录下的报表文件用于用户操作
AnsiString ExcelFileName =
GetCurrentDir();+"\\report\\table.xls";
if(!FileExists(ExcelFileName))
{
Application->MessageBox("Excel表文件不存在,无法打开!",
"错误",MB_ICONSTOP|MB_OK);
return;
}
try
{
Ex = Variant::CreateObject("Excel.Application");
}
catch(...)
{
Application->MessageBox("无法启动Excel","错误",MB_ICONSTOP|MB_OK);
return;
}
file://使Excel可见
Ex.OlePropertySet("Visible",true);
file://打开Excel表格文件Table.xls
Ex.OlePropertyGet("WorkBooks").OleProcedure("Open",ExcelFileName.c_str());
}
catch(...)
{
Application->MessageBox("操作Excel表格错误!","错误",MB_ICONSTOP|MB_OK);
Ex.OleFunction("Quit");
}
}
===========================
用C++Builder操纵Excel
发布者:51CTO 日期: 2005-11-21 14:23:00 浏览次数:0 (共有_条评论) 查看评论 | 我要评论
Microsoft Excel作为一个功能强大的电子表格处理软件,已经得到了广泛的应用。在数据库应用软件开发过程中,如果能实现数据库与Excel文件的数据交换,那么一方面能增加数据库数据的来源,另一方面也能方便用户对数据库数据的进一步处理。
C++ Builder是一个可视化快速应用程序开发工具,它提供的OLE Automation机制使得开发人员在应用程序中就能调用Excel,实现数据交换。
在C++ Builder中调用Excel,首先要为Excel建立一个OLE对象,然后通过设定该对象的属性和调用该对象的方法来操纵Excel。C++ Builder通过CreateOleObject()来建立OLE对象;用OlePropertySet(propname,value)来设置OLE对象的属性;用OlePropertyGet(propname)获得OLE对象的属性;通过OleFunction(oleFuncName,[val,...])和OleProcedure(oleProcName,[val,...])来调用OLE对象的方法。
C++ Builder中使用OLE自动化操纵Excel,必须掌握Excel的自动化对象及VBA关于Excel的对象方法和属性,这些都在Microsoft Office(完全安装)的VBAXL8.HLP帮助文件中可以找到,在此就不再赘述。下面以将数据库中的数据转到Excel工作薄中为例,说明C++ Builder操纵Excel的具体方法。
首先新建一个表单Form1,保存单元文件Unit1.cpp,保存工程文件Project1.bpr。然后在表单中加入数据访问控件TTable,将Name属性设为Table1,DatabaseName属性设为BCDEMOS,TableName属性设为Country.db。在表单中加入一个按钮控件TButton,将其Name属性设为Button1,Caption属性设为 “转换为Excel文件”。双击Button1,在Button1Click()函数中加入如下代码:
Variant ex,newxls;
int i,j=1;
try
{
ex=CreateOleObject(″Excel.Application″); //启动Excel
}
catch(...)
{
ShowMessage(″无法启动Excel″);
}
ex.OlePropertySet(″Visible″,(
Variant)true); //使Excel启动后可见
newxls=(ex.OleFunction(″Workbooks″)).OleFunction(″Add″);//新建一个工作薄
Table1-〉Active=true;
//打开数据库
Table1-〉First();
for(i=0;i〈Table1-〉FieldCount;i++)
//将字段名写到工作薄的第一行
{
(ex.OleFunction(″Cells″)).OlePropertySet(″Item″,(Variant)1,(Variant)(i+1),(Variant)Table1-〉Fields-〉FieldName);
}
while(!Table1-〉Eof)
//将数据库中的记录依次写到工作薄中
{
j=j+1;
for(i=0;i〈Table1-〉FieldCount;i++)
{
(ex.OleFunction(″Cells″)).OlePropertySet(″Item″,(Variant)j,(Variant)(i+1),
(Variant)Table1-〉Fields-〉AsString);
}
Table1-〉Next();
}
newxls.OleFunction(″SaveAs″,(Variant)filename);
//保存工作薄,filename是工作薄的全文件名
ex.OleFunction(″Quit″);
//退出Excel,释放OLE对象
注意,要使用OLE自动化对象,在编译之前还必须在Unit1.cpp文件前面加上#include ″ComObj.hpp″。
运行程序就可以实现将数据库中的数据转换到Excel工作薄中。同样的道理,使用OlePropertyGet()函数,也可以将Excel工作薄中的数据读到数据库中去。
以上代码在Windows 98操作系统、C++ Builder 3.0下调试运行通过。
======================
C++Builder 设置Excel 列宽 行高 .
分类: c++ builder 2010-03-18 22:14 111人阅读 评论(0) 收藏 举报
https://www.sodocs.net/doc/e82052086.html,/miderph84/archive/2009/03/17/3998235.aspx
要在应用程序中控制Excel的运行,首先必须在编制自动化客户程序时包含 Comobj.hpp
#include "Comobj.hpp"
C++ Builder把Excel自动化对象的功能包装在下面的四个Ole Object Class函数中,应用人员可以很方便地进行调用。
设置对象属性:void OlePropertySet(属性名,参数……);
获得对象属性:Variant OlePropertyGet(属性名,参数……);
调用对象方法:1) Variant OleFunction(函数名,参数……);
2) void OleProcedure(过程名,参数……);
在程序中可以用宏定义来节省时间:
#define PG OlePropertyGet
#define PS OlePropertySet
#define FN OleFunction
#define PR OleProcedure
举例:
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add");
可写为
ExcelApp.PG("workbooks").FN("Add");
◎ 设置列宽
ExcelApp.PG("Columns", 1).PS("ColumnWidth", 22);
或者
Range = ExcelApp.PG("Cells", 1, 3);
Range.PS("ColumnWidth", 22);
◎ 设置行高
ExcelApp.PG("Rows", 2).PS("RowHeight", 25);
或者
Range = ExcelApp.PG("Cells", 2, 1);
Range.PS("RowHeight", 25);
或者另一个方法 (没试过)
eworkbook.worksheets[1].columns.autofit;//如不自定义宽度,可以使各列自动对齐
==================
/***********************************************
*************************************************
乌龟代码
*************************************************************************************************/
/******* 导出到excel */
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:/temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel */
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:/test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions
/*动态文件名
declare @fn varchar(20),@s varchar(1000)
set @fn = 'c:/test.xls'
set @s ='''Microsoft.Jet.OLEDB.4.0'',
''Data Source="'+@fn+'";User ID=Admin;Password=;Extended properties=Excel 5.0'''
set @s = 'SELECT * FROM OpenDataSource ('+@s+')...sheet1
ype=DBF;SourceDB=c:/',
'select * from [aa.DBF]')
select * from 表
/*说明:
SourceDB=c:/ 指定foxpro表所在的文件夹
aa.DBF 指定foxpro表的文件名. */
/*************导出到Access********************/
insert into openrowset('Microsoft.Jet.OLEDB.4.0',
'x:/A.mdb';'admin';'',A表) select * from 数据库名..B表
/*************导入Access********************/
insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
'x:/A.mdb';'admin';'',A表)
/*文件名为参数*/
declare @fname varchar(20)
set @fname = 'd:/test.mdb'
exec('SELECT a.* FROM opendatasource(''Microsoft.Jet.OLEDB.4.0'',
'''+@fname+''';''admin'';'''', topics) as a ')
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="f:/northwind.mdb";Jet OLEDB:Database Password=123;User ID=Admin;Password=;')...
==============================
取宽度
var ExcelApp: Variant;
ExcelApp := CreateOleObject( 'Excel.Application' );
ExcelApp.ActiveSheet.Columns[1].ColumnsWidth;
=====================================
参考资料:https://www.sodocs.net/doc/e82052086.html,/zjt621/archive/2007/01/30/1498104.aspx
要在应用程序中控制Excel的运行,首先必须在编制自动化客户程序时包含Comobj.hpp
#include "Comobj.hpp"
C++ Builder把Excel自动化对象的功能包装在下面的四个Ole Object Class函数中,应用人员可以很方便地进行调用。
设置对象属性:Variant OlePropertySet(属性名,参数……);
获得对象属性:void OlePropertyGet(属性名,参数……);
调用对象方法:1) Variant OleFunction(函数名,参数……);
2) void OleProcedure(过程名,参数……);
在程序中可以用宏定义来节省时间:
#define PG OlePropertyGet
#define PS OlePropertySet
#define FN OleFunction
#define PR OleProcedure
举例:
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add")可写为
ExcelApp.PG("workbooks").FN("Add")
C++ Builder中使用OLE控制Excel2000,必须掌握Excel2000的自动化对象及Microsoft Word Visual Basic帮助文件中的关于Excel的对象、方法和属性。对象是一个Excel元素,属性是对象的一个特性或操作的一个方面,方法是对象可以进行的动作。
首先定义以下几个变量:
Variant ExcelApp,Workbook1,Sheet1,Range1;
1、Excel中常用的对象是:Application,Workbooks,Worksheets等。
(1)创建应用对象:如:
Variant ExcelApp;
ExcelApp=Variant::CreateObject ("Excel.Application");
或者
ExcelApp=CreateOleObject ("Excel.Application");
(2)创建工作簿对象:
Variant WorkBook1;
WorkBook1=ExcelApp.O
lePropertyGet("ActiveWorkBook");
(3)创建工作表对象:
Variant Sheet1;
Sheet1=WorkBook1.OlePropertyGet("ActiveSheet");
(4)创建区域对象:
Variant Range;
Range=Sheet1.OlePropertyGet("Range","A1:A10");
2、常用的属性操作:
(1)使Excel程序不可见
ExcelApp.OlePropertySet("Visible",(Variant)false);
(2)新建EXCEL文件:
(a):新建系统模板的工作簿
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add") //默认工作簿
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",1) //单工作表
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",2) //图表
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",3) //宏表
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",4) //国际通用宏表
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",5) //与默认的相同
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add",6) //工作簿且只有一个表
(b):新建自己创建的模板的工作簿
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add","C:\\Templates\\result.xlt");
(3)打开工作簿:
ExcelApp.OlePropertyGet("workbooks").OleFunction("open","路径名.xls")
(4)保存工作簿:
WorkBook1.OleFunction("Save"); //保存工作簿
WorkBook1.OleFunction("SaveAs","文件名"); //工作簿保存为,文件路径注意用“\\”
(5)退出EXCEL:
ExcelApp.OleFunction ("Quit");
ExcelApp=Unassigned;
(6)操作工作表
(a)选择选择工作表中第一个工作表
Workbook1.OlePropertyGet("Sheets",1).OleProcedure("Select");
Sheet1=Workbook1.OlePropertyGet("ActiveSheet");
(b)重命名工作表
Sheet1.OlePropertySet("Name","Sheet的新名字");
(c)当前工作簿中的工作表总数
int nSheetCount=Workbook1.OlePropertyGet("Sheets").OlePropertyGet("Count");
(7)操作行和列:
(a)获取当前工作表中有多少行和多少列:
Sheet1.OlePropertyGet("UsedRange").OlePropertyGet("Columns").OlePropertyGet("Count"); //列数
Sheet1.OlePropertyGet("UsedRange").OlePropertyGet("Rows").OlePropertyGet("Count"); //行数
(b)设置列宽
ExcelApp.OlePropertyGet("Columns",1).OlePropertySet("ColumnWidth",22);
(c)设置行高
ExcelApp.OlePropertyGet("Rows",2).OlePropertySet("RowHeight",25);
(d)在工作表最前面插入一行
Sheet1.OlePropertyGet("Rows",1).OleProcedure("Insert");
(e)删除一行
ExcelApp.OlePropertyGet("Rows",2).OleProcedure("Delete"); //将第2行删除
(7)操作单元格
(a):设置单元格字体
Sheet1.OlePropertyGet("Cells",1,1).OlePropertyGet("Font").OlePropertySet("Name","隶书"); //字体
Sheet1.OlePropertyGet("Cells",2,3).OlePropertyGet("Font").OlePropertySet("size",28); //大小
(b):设置所选区域字体
Range.OlePropertyGet("Cells").OlePropertyGet("Font").OlePropertySet("Size",28);
Range.OlePropertyGet("Cells").OlePropertyGet("Font").OlePropertySet("Color",RGB(0,0,255));
其中参数的设置:
Font Name : "隶书" //字体名称
Size : 12 //字体大小
Color : RGB(*,*,*) //颜色
Underline : true/false //下划线
Italic: true/false //斜体
(c)设置单元格格式为小数百分比
Sheet1.OlePropertyGet("Cells",1,1).OlePropertySet("NumberFormatLocal","0.00%");
(8)单元格的合并:
(a)Range=Sheet1.OlePropertyGet("Range", "A1:A2"); //A1和A2单元格合并
(b)String strRange="A"+IntToStr(j)+":"+"C"+IntToStr(j); //比如:A1:C5
Range1=Sheet1.OlePropertyGet("Range",strRange.c_str()); //可以用变量控制单元格合并
Range1.OleFunction("Merge",false);
(9)读写单元格:
(a):指定单元格赋值
String strValue="abcdefg";
Sheet1.OlePropertyGet("Cells",3,6).OlePropertySet("Value",strValue.c_str());
Sheet1.OlePropertyGet("Cells",j,1).OlePropertySet("Value","总记录:"+String(j-6));
(b):所选区域单元格赋值
Range.OlePropertyGet("Cells").OlePropertySet("Value",10);
(c):所选区域行赋值
Range.OlePropertyGet("Rows",1).OlePropertySet("Value",1234);
(d):工作表列赋值
Sheet1.OlePropertyGet("Columns",1).OlePropertySet("Value",1234);
(c):读取取值语句:
String strValu
e=Sheet1.OlePropertyGet("Cells",3,5).OlePropertyGet("Value");
(10)区域选择:
Range1.OlePropertyGet("Cells").OleFunction("Select");
(11)窗口属性:
(a)显示属性
ExcelApp.OlePropertySet("Windowstate",3); //最大化显示
1---------xlNormal //正常显示
2---------xlMinimized //最小化显示
3---------xlMaximized //最大化显示
(b)状态栏属性
ExcelApp.OlePropertySet("StatusBar","您好,请您稍等。正在查询!");
ExcelApp.OlePropertySet("StatusBar", false); //还原成默认值
(c)标题属性:
ExcelApp.OlePropertySet("Caption","查询系统");
另外,为保证程序能正常运行,需要在程序中判断目标机器是否安装了Office;
try
{
ExcelApp=Variant::CreateObject ("Excel.Application");
}
catch(...)
{
ShowMessage("运行Excel出错,请确认安装了Office");
return;
}
=========================================
用OLE操作Excel(目前最全的资料)(04.2.19更新)
本文档部分资料来自互联网,大部分是ccrun(老妖)在Excel中通过录制宏-->察看宏代码-->转为CB代码而来.本文档不断更新中.欢迎大家关注.
要在应用程序中控制Excel的运行,首先必须在编制自动化客户程序时包含Comobj.hpp
#include "Comobj.hpp"
C++ Builder把Excel自动化对象的功能包装在下面的四个Ole Object Class函数中,应用人员可以很方便地进行调用。
设置对象属性:void OlePropertySet(属性名,参数……);
获得对象属性:Variant OlePropertyGet(属性名,参数……);
调用对象方法:1) Variant OleFunction(函数名,参数……);
2) void OleProcedure(过程名,参数……);
在程序中可以用宏定义来节省时间:
#define PG OlePropertyGet
#define PS OlePropertySet
#define FN OleFunction
#define PR OleProcedure
举例:
ExcelApp.OlePropertyGet("workbooks").OleFunction("Add");
可写为
ExcelApp.PG("workbooks").FN("Add");
C++ Builder中使用OLE控制Excel2000,必须掌握Excel2000的自动化对象及Microsoft Word Visual Basic帮助文件中的关于Excel的对象、方法和属性。对象是一个Excel元素,属性是对象的一个特性或操作的一个方面,方法是对象可以进行的动作。
首先定义以下几个变量:
Variant ExcelApp,Workbook1,Sheet1,Range1;
1、Excel中常用的对象是:Application,Workbooks,Worksheets等。
★创建应用对象★
Variant Excel
App;
ExcelApp = Variant::CreateObject ("Excel.Application");
或者
ExcelApp = CreateOleObject ("Excel.Application");
★创建工作簿对象★
Variant WorkBook1;
WorkBook1 = ExcelApp.PG("ActiveWorkBook");
★创建工作表对象★
Variant Sheet1;
Sheet1 = WorkBook1.PG("ActiveSheet");
★创建区域对象★
Variant Range;
Range = Sheet1.PG("Range","A1:A10");
或者使用
Excel.Exec(PropertyGet("Range")<<"A1:C1").Exec(Procedure("Select"));
2、常用的属性操作:
★使Excel程序不可见★
ExcelApp.PS("Visible", (Variant)false);
★新建EXCEL文件★
◎ 新建系统模板的工作簿
ExcelApp.PG("workbooks").FN("Add") //默认工作簿
ExcelApp.PG("workbooks").FN("Add", 1) //单工作表
ExcelApp.PG("workbooks").FN("Add", 2) //图表
ExcelApp.PG("workbooks").FN("Add", 3) //宏表
ExcelApp.PG("workbooks").FN("Add", 4) //国际通用宏表
ExcelApp.PG("workbooks").FN("Add", 5) //与默认的相同
ExcelApp.PG("workbooks").FN("Add", 6) //工作簿且只有一个表
或者使用ExcelApp的Exec方法
Excel.Exec(PropertyGet("Workbooks")).Exec(Procedure("Add"));
◎ 新建自己创建的模板的工作簿
ExcelApp.PG("workbooks").FN("Add", "C:\\Temp\\result.xlt");
★打开工作簿★
ExcelApp.PG("workbooks").FN("open", "路径名.xls")
★保存工作簿★
WorkBook1.FN("Save"); //保存工作簿
WorkBook1.FN("SaveAs", "文件名");//工作簿保存为,路径注意用"\\"
★退出EXCEL★
ExcelApp.FN ("Quit");
ExcelApp = Unassigned;
或者
ExcelApp.Exec(Procedure("Quit"));
★操作工作表★
◎ 选择选择工作表中第一个工作表
Workbook1.PG("Sheets", 1).PR("Select");
Sheet1 = Workbook1.PG("ActiveSheet");
◎ 重命名工作表
Sheet1.PS("Name", "Sheet的新名字");
◎ 当前工作簿中的工作表总数
// 本文转自 C++Builder 研究 - https://www.sodocs.net/doc/e82052086.html,/article.asp?i=529&d=0iezy5
int nSheetCount=Workbook1.PG("Sheets").PG("Count");
★操作行和列★
◎ 获取当前工作表中有多少行和多少列:
Sheet1.PG("UsedRange").PG("Columns").PG("Count"); //列数
Sheet1.PG("UsedRange").PG("Rows").PG("Count"); //行数
◎ 设置列宽
ExcelApp.PG("Columns", 1).PS("ColumnWidth", 22);
或者
Range = ExcelApp.PG("Cells", 1, 3);
Range.PS("ColumnWidth", 22);
◎ 设置行高
ExcelApp.PG("Rows", 2).PS("RowHeight", 25);
或者
Range = ExcelApp
.PG("Cells", 2, 1);
Range.PS("RowHeight", 25);
◎ 在工作表最前面插入一行
Sheet1.PG("Rows", 1).PR("Insert");
◎ 删除一行
ExcelApp.PG("Rows", 2).PR("Delete"); //将第2行删除
// 本文作者:ccrun ,如转载请保证本文档的完整性,并注明出处。
// 欢迎光临 C++ Builder 研究 https://www.sodocs.net/doc/e82052086.html,
// 摘自:https://www.sodocs.net/doc/e82052086.html,/doc/go.asp?id=529
★操作单元格★
◎ 设置单元格字体
Sheet1.PG("Cells", 1, 1).PG("Font").PS("Name", "隶书"); //字体
Sheet1.PG("Cells", 2, 3).PG("Font").PS("size", 28); //大小
◎ 设置所选区域字体
Range.PG("Cells").PG("Font").PS("Size", 28);
Range.PG("Cells").PG("Font").PS("Color", RGB(0, 0, 255));
其中参数的设置:
Font Name : "隶书" //字体名称
Size : 12 //字体大小
Color : RGB(*,*,*) //颜色
Underline : true/false //下划线
Italic: true/false //斜体
◎ 设置单元格格式为小数百分比
Sheet1.PG("Cells", 1, 1).PS("NumberFormatLocal", "0.00%");
◎ 设定单元格的垂直对齐方式
Range = ExcelApp.PG("Cells", 3, 4);
// 1=靠上 2=居中 3=靠下对齐 4=两端对齐 5=分散对齐
Range.PS("VerticalAlignment", 2);
◎ 设定单元格的文本为自动换行
Range = ExcelApp.PG("Cells", 3, 4);
Range.PS("WrapText", true);
★单元格的合并★
◎ Range = Sheet1.PG("Range", "A1:A2"); //A1和A2单元格合并
String strRange = "A" + IntToStr(j) + ":" + "C" + IntToStr(j); //比如:A1:C5
Range1=Sheet1.PG("Range", strRange.c_str()); //可以用变量控制单元格合并
Range1.FN("Merge", false);
★读写单元格★
◎ 指定单元格赋值
String strValue = "abcdefg";
Sheet1.PG("Cells", 3, 6).PS("Value", strValue.c_str());
Sheet1.PG("Cells", j, 1).PS("Value", "总记录:" + String(j-6));
或者使用
Excel.Exec(PropertyGet("Cells")<<1<<3).Exec(PropertySet("Value")<<15);
◎ 所选区域单元格赋值
Range.PG("Cells").PS("Value", 10);
◎ 所选区域行赋值
Range.PG("Rows",1).PS("Value", 1234);
◎ 工作表列赋值
Sheet1.PG("Columns",1).PS("Value", 1234);
◎ 读取取值语句:
String strValue = Sheet1.PG("Cells", 3, 5).PG("Value");
★窗口属性★
◎ 显示属性
ExcelApp.PS("Windowstate", 3); //最大化显示
1---------xlNormal //正常显示
2---------xlMinimized //最小化显示
3---------xlMaximized //最大化显示
◎ 状态栏属性
ExcelApp.PS("StatusBar", "您好,请您稍等。正在查询!");
ExcelApp.PS("StatusBar", false); //还原成默认值
◎ 标题属性:
ExcelApp.PS("Caption", "查询系统");
3、操作图表
★添加图表
Variant Chart;
Chart = ExcelApp.Exec(PropertyGet("Charts")).Exec(Function("Add"));
ExcelApp.Exec(PropertySet("Visible") << true);
Chart.Exec(PropertySet("Type") << -4100);
★滚动图表
for(int nRotate=5; nRotate <= 180; nRotate += 5)
{
Chart.Exec(PropertySet("Rotation") << nRotate);
}
for (int nRotate = 175; nRotate >= 0; nRotate -= 5)
{
Chart.Exec(PropertySet("Rotation") << nRotate);
}
另外,为保证程序能正常运行,需要在程序中判断目标机器是否安装了Office;
try
{
ExcelApp = Variant::CreateObject ("Excel.Application");
}
catch(...)
{
ShowMessage("运行Excel出错,请确认安装了Office");
return;
}
#include "comobj.hpp"
//---------------------------------------------------------------------------
// 对指定Excel文件中的指定列进行排序
// strExcelFileName : excel文件名
// nCol : 指定的列号
// nSortStyle : 1:升序,2:降序
void SortExcelColumn(String strExcelFileName, int nCol, int nSortStyle)
{
Variant vExcelApp, vWorkbook, vRange;
vExcelApp = Variant::CreateObject("Excel.Application");
vExcelApp.OlePropertySet("Visible", false);
vExcelApp.OlePropertyGet("WorkBooks").OleProcedure("Open", strExcelFileName.c_str());
vWorkbook = vExcelApp.OlePropertyGet("ActiveWorkbook");
vExcelApp.OlePropertyGet("Columns", nCol).OleProcedure("Select");
vExcelApp.OlePropertyGet("ActiveSheet").OlePropertyGet("Cells", 1, nCol).OleProcedure("Select");
vRange = vExcelApp.OlePropertyGet("Selection");
vRange.Exec(Function("Sort")<
vWorkbook.OleProcedure("Save");
vWorkbook.OleProcedure("Close");
vExcelApp.OleFunction("Quit");
vWorkbook = Unassigned;
vExcelApp = Unassigned;
ShowMessage("ok");
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// 对C:\123\123.xls文件中第一个Sheet的第四列进行升序排序
SortExcelColumn("C:\\123\\123.xls", 4, 1);
}
excel打印页面设置
//excel_app.OlePropertyGet("ActiveWindow").OlePropertySet("DisplayGridlines",False); //不显示背景的网格线;
my_worksheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHorizontally",2/0.035);//页面水平居中:
my_worksheet.OlePropertyGet("PageSetup").OlePropertySet("PrintGridLines",true);//打印表格线;
my_worksheet.OlePropertyGet("PageSetup").OlePr
opertySet("Orientation",2); //Orientation=poLandscape;1;2为横向;
excel_app.OlePropertyGet("ActiveWindow").OlePropertyGet("SelectedSheets").OleFunction("PrintPreview");//打印预览
给你个完整的例子:
#include "comobj.hpp"
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Variant vExcelApp, vSheet;
AnsiString strFileName = "C:\\123\\123.xls";
if(!FileExists(strFileName))
return;
// 启动excel
vExcelApp = CreateOleObject("Excel.Application");
// 使Excel程序不可见
vExcelApp.OlePropertySet("Visible", true);
// 打开Excel文档
vExcelApp.OlePropertyGet("Workbooks").
OleFunction("Open", strFileName.c_str());
// 获得当前活动的Sheet
vSheet = vExcelApp.OlePropertyGet("ActiveSheet");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintTitleRows", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintTitleColumns", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintArea", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftHeader", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHeader", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightHeader", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftFooter", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterFooter", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightFooter", "");
vSheet.OlePropertyGet("PageSetup").OlePropertySet("LeftMargin", 0.748031496062992);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("RightMargin", 0.748031496062992);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("TopMargin", 0.984251968503937);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("BottomMargin", 0.984251968503937);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("HeaderMargin", 0.511811023622047);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("FooterMargin", 0.511811023622047);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintHeadings", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintGridlines", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintComments", -4142); // xlPrintNoComments
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PrintQuality", 600);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("CenterHorizontally", true);
vSheet.OlePropertyGet("PageSe
tup").OlePropertySet("CenterVertically", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("Orientation", 1); // xlPortrait
vSheet.OlePropertyGet("PageSetup").OlePropertySet("Draft", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("PaperSize", 9); // xlPaperA4
vSheet.OlePropertyGet("PageSetup").OlePropertySet("FirstPageNumber", -4105); // xlAutomatic
vSheet.OlePropertyGet("PageSetup").OlePropertySet("Order", 1); // xlDownThenOver
vSheet.OlePropertyGet("PageSetup").OlePropertySet("BlackAndWhite", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("Zoom", false);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("FitToPagesWide", 1);
vSheet.OlePropertyGet("PageSetup").OlePropertySet("FitToPagesTall", 1);
// 保存这个工作簿
vExcelApp.OlePropertyGet("ActiveWorkBook").OleProcedure("Save");
// 退出Excel程序
vExcelApp.OleFunction("Quit");
ShowMessage("设置成功!");
}
=========================
我们在对日开发中Delphi控制Excel的经验如下:
Delphi 5 控制Excel
作者:吴晓勇,孙唏瑜
时间:2001年11月20日
(一) 使用动态创建的方法
首先创建 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].Clear
Contents;
13) 设置第一行字体属性:
ExcelApp.ActiveSheet.Rows[1]https://www.sodocs.net/doc/e82052086.html, := '隶书 ';
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 := '第&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.拷贝整个工作表:
https://www.sodocs.net/doc/e82052086.html,ed.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]https://www.sodocs.net/doc/e82052086.html, := '隶书 ';
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 := '第&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.拷贝整个工作表:
https://www.sodocs.net/doc/e82052086.html,ed.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.HasT
===================================
AnsiString strRange = "B10:C10 "; //假设范围 合并单元格
AnsiString temp= "True ";
ERange = Sheet.OlePropertyGet( "Range ",strRange.c_str());
ERange.OlePropertySet( "MergeCells ",(TVariant)temp.c_str());
=========================
如何利用C++ Builder实现对Excel97 的调用
我们在进行数据库软件的开发时,一般都要进行大量的报表设计,虽然我们可以利用crystal report 或程序自带的报表工具进行报表设计,但是当涉及到要设计多重报表或交叉报表时、我们一般都会感到自己力不从心。有时虽然想利用excel作为前台报表,但却找不到相关接口只能作罢。其实我们只要知道excel的接口结构,就能够方便的实现对excel的调用。
原理:在excel 中程序接口一般分为3层 ,分别为:exelapplication、excelbook、excelsheet 其中exelapplication代表excel程序,excelbook代
表excel程序当前的工作本,excelsheet代表excelbook当前激活的表格,因此在启动excel程序时要按此序分别启动,这样就能实现对excel报表的操作。
现举例为例介绍如下:
一、在import type library中加入 excel8.olb,在include 子目录下生成excel_tlb.h文件.
二、在bcb4.0中form1中添加button1、button2、button3、table1,并存盘为project1。
三、在unit1.h中加入头文件 #include "..excel_tlb.h"
在private中加入
private:
tcom_application application; file://定义excelapplication对象//
worksheetptr worksheet; // 定义excelsheet对象//
rangeptr firstcol ; file://定义列对象//
rangeptr range file://定义表格操作范围//
四、在button1的onclikc事件中添加如下代码:
void __fastcall tform1::button1click(tobject *sender)
{//启动excel//
const int xlwbatchart = -4109;
const int xlwbatworksheet = -4167;
if (! application)
application = coapplication_::create(); file://建立于excel程序的连接//
application->set_visible(0, true);//打开excel程序//
application->workbooks->add(xlwbatworksheet);//创建只含有一个excelsheet的excelbook//
worksheet = application->workbooks->get_item(1)->worksheets->get_item(1);//取得该表对象//
worksheet->name = widestring("database date");//建立该表的名称//
}
五、在button2的onclikc事件中添加如下代码:
void __fastcall tform1::button2click(tobject *sender)
{//添加数据//
int i, j;
table1->databasename="dbdemos";
table1->tablename="author.db";
table1->open( );
for( i=0;i
worksheet->cells->set__default(1,i,table1->fileds->fileds[i]->filedname);//在指定的位置加入字段名//
table1->first();
j=2;
while( !table1->eof( ))
{
for( i=0;i
worksheet->cells->set__default(j,i, table1->fields->fileds[i]->asstring);////在指定的位置加入数据库的内容//
table1->next( );
j++;
}
}
六、在button3的onclikc事件中添加如下代码:
void __fastcall tform1::button3click(tobject *sender)
{//表格设置//
range = m_worksheet->get_range("c1:f20");//设置表格操作范围//
range->font->size=12;//设置字体大小//
range->columns->interior->colorindex = 3;//设置表格表格颜色//
range->borders->linestyle = xlcontinuous;//设置表格边框//
firstcol = m_worksheet->columns->get__default(3 );//取得当前表格的第三列对象//
firstcol->columnwidth = 25; // 设置对象宽度//