您的位置:首页 > 编程语言 > C语言/C++

vs环境下,用c++使用微软word提供的com接口

2016-06-15 22:30 633 查看
主要需要#import 三个文件VBE6EXT.OLB,MSO.DLL,MSWORD.OLB,这样就可以使用主要的函数。

_ApplicationPtr word.CreateInstance(__uuidof(MSWORD::Application); //代表word本身的智能

word->PutVisible(VARIANT_TRUE);  //显示word,调用这个函数可以把word界面显示出来,不调用的话就不会显示,但任然可以在调用word提供的接口在后台对word进行编辑操作。

//打开某个文件

wstring file_name;

_bstr_t path;

word->ChangeFileOpenDirectory(path); //这个是关键,要先调用这个转换到文件所在路径,不能直接用全路径打开word文档,不然2013版会崩溃,2010版不会。

word->GetDocuments()->Open(&CComVariant(file_name.c_str()), &CComVariant(true),&CComVariant(false), &CComVariant(false), &CComVariant(""),&CComVariant(""), &CComVariant(false), &CComVariant(""), &CComVariant(""),&CComVariant(wdOpenFormatAuto), &CComVariant(""));

SelectionPtr ptr = word->GetSelection(); //获取光标对象只能指针,插入文字之类的操作都在这个对象里面,或者可以通过这个指针获得的对象里面。

ptr->TypeText(text);//在光标位置插入文字

ptr->InlineShapes->AddPicture(picture);//插入图片,参数为图片路径

ptr->TypeParagraph();//回车

//下面是对光标状态的设置,设置完状态,再插入文字,那文字就是那种状态,直到重新改变设置,相当于一种状态机。

ptr->GetParagraphFormat()->PutAlignment(wdAlignParagraphCenter); //设置居中对齐

ptr->PutStyle(&CComVariant(wdStyleNormal)); //设置文字类型,普通文字或者标题等,这是普通文字

ptr->PutStyle(&CComVariant(level)); //设为某级标题

//光标移动相关

ptr->WholeStory();//选中全文

ptr->MoveRight();//光标移动,先选中全文再又移就是把光标至于文档末尾。

wstring BookMark;//书签名

ptr->GoTo(COleVariant((short)-1),COleVariant((short)0),

                    COleVariant((short)0),COleVariant(BookMark.c_str()));    //将光标转移到书签位置

//当光标在表格中时,移动到其他单元格

int Num; //移动格数 

ptr->MoveRight(COleVariant((short)1),COleVariant((short)Num),

                    COleVariant((short)0));    //光标按照单元格数向右移动。

//合并单元格

TablesPtr ptr_tables = ptr->Document->Tables; //获取文档中的所有表格对象指针,用类型的方法也可以获得所有书签对象指针

long index; //表格序号

TablePtr ptr_table = ptr_tables->Item(index); //获取某个表格的指针

CellPtr p_cell_start = ptr_table->Cell(row1, Col1);//获取起始单元格,参数为单元格所在行列

cellPtr p_cell_end = ptr_table->Cell(row, Col);//结束单元格

p_cell_start->Merge(p_cell_end); //合并单元格

//另存为并退出

word->ChangeFileOpenDirectory(path); //前往目标路径

word->GetActiveDocument()->SaveAs(&CComVariant(file_name.c_str()));//保存文件名

ptr->Release();

word->Quit(&CComVariant(true));//退出

活用书签来跳转光标,就能在文档中的任何位置进行文字或图片的插入操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: