C++将DBGrid中数据导出到Word和Excel

C++将DBGrid中数据导出到Word和Excel,第1张

C++将DBGrid中数据导出到Word和Excel,第2张

经常看到网友发帖询问如何将DBGrid中的内容导出到Excel或Word文档中,所以我花了一些时间编写了以下两个函数,分别将DBGrid中的数据导出到Word和Excel文档中。需要注意的是,DBGrid中的数据并不代表数据库中的所有数据,因为数据集在打开时可能会被过滤,这取决于用户如何打开数据集。简而言之,DBGrid中显示多少数据就会导出多少。

1.将DBGrid中的内容导出到Word文档中

// - .-
void _ _ fast call dbgrid 2 word(TDBGrid * dbg,String strDocFile)
{
if(!g-> data source-> dataset-> active)//数据集返回
不打开返回;
Variant vWordApp,vTable,VCell
try
{
vword app = Variant::CreateObject(" Word。应用”);
}
Catch(...)
{
MessageBox (0,"启动Word时出错,可能没有安装Word。",“DBGrid2Word”,MB _ OK | MB _ icon error);
vword app = Unassigned;
退货;
}
/隐藏Word接口
vwardapp.ole属性集(" visible ",false);
//创建新文档
vwerdapp . olepropertyget(" documents ")。ole function(" add ");
Variant vSelect = vWordApp。OlePropertyGet(" Selection ");
//设置字体大小
vselect . olepropertyget(" font ")。olepropertyset ("size ",dbg-> font-> size);
vSelect。OlePropertyGet("Font ")。OlePropertySet("Name ",dbg-> Font-> Name . c _ str());
//要插入表中的行数
int n rowcount(dbg-> data source-> dataset-> record count+1);
nRowCount = nRowCount < 2?2:nRowCount;
//要插入到表中的列数
int ncolcount(dbg-> columns-> count);
nColCount = nColCount < 1?1:nColCount;
//在Word文档
vwardapp.olepropertyget("活动文档")中插入一个行数和列数与DBGrid相同的表格。olepropertyget("表格")。oleprocedure ("add ",
vselect . olepropertyget(" range "),
nrowcount,//行数
nColCount,//列数
1,//defaulttablebehavior:= wd word 9 table behavior
0//autofitbehavior:= wdautofitfixed
//操作此表
vtable = vword app . olepropertyget("活动文档")。
olefunction ("range ")。olepropertyget("表格")。olefunction (
//设置(int I = 0;I {
int nColWidth = dbg-> Columns-> Items[I]-> Width;表。OlePropertyGet("Columns ")。OleFunction("Item ",i + 1)
。OlePropertySet(" PreferredWidthType ",3);//wdPreferredWidthPoints
vTable。OlePropertyGet("Columns ")。OleFunction("Item ",i + 1)
。OlePropertySet("PreferredWidth ",nColWidth);
}
/在Word table
中为(int j = 0;jColumns-> Count;j++)
{
vCell = vTable。OleFunction("Cell ",1,j+1);
vCell。OlePropertySet("Range ",dbg-> Columns-> Items[j]-> field name . c _ str());
//列名单元格背景色//wdcolorgray 125
vcell . olepropertyget(" shading ")。olepropertyset(" BackgroundPatternColor ",14737632);
}
/将DBGrid中的数据写入Word表
DBG->数据源->数据集-> first();
for(int I = 0;I {
//63 63 72 75 6E 2E 63 6F 6D
for(int j = 0;jColumns-> Count;j++)
{
vCell = vTable。OleFunction("Cell ",i + 2,j+1);
vCell。OlePropertySet("Range ",
dbg-> data source-> DataSet-> field by name(
dbg-> Columns-> Items[j]-> field name)-> asstring . c _ str());
}
dbg-> data source-> DataSet-> Next();
}
/保存Word文档并退出
vjordapp.olepropertyget("活动文档")。ole过程("另存为",strdocfile . c _ str());
vWordApp。OlePropertyGet("ActiveDocument ")。ole procedure(" Close ");
Application-> process messages();
vWordApp。ole procedure(" Quit ");
Application-> process messages();
vword app = Unassigned;
//作业完成
MessageBox (0," DBGrid2Word转换完成!",“DBGrid2Word”,MB _ OK | MB _ icon information);
}

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » C++将DBGrid中数据导出到Word和Excel

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情