【当前博文转载自:http://www.cppblog.com/codeart/archive/2010/08/31/125430.aspx】
c++操作word接口
注意事项:1多用Range,少用Selection,因为Word中,Selection对象只有一个。【1】开启word
_ApplicationPtr word_app;
HRESULThr
=
word_app.CreateInstance(
"
Word.Application
"
, NULL);
【2】新建一个文档
HRESULT
COleVariant vTrue((
short
)TRUE),vFalse((
short
)FALSE),vOpt((
long
)DISP_E_PARAMNOTFOUND, VT_ERROR);
DocumentsPtrdocs;
_DocumentPtroDoc;
docs
=
word_app
->
GetDocuments();
doc
=
docs
->
Add(vOpt, vOpt, vOpt, vOpt);
【3】设置文档的页面布局
DocumentsPtr
_DocumentPtr
docs
doc
PageSetupPtr page_setup
=
doc
->
GetPageSetup();
page_setup -> PutTopMargin( 0 );
page_setup -> PutBottomMargin( 0 );
page_setup -> PutRightMargin( 0 );
page_setup -> PutLeftMargin( 0 );
【4】插入文本
page_setup -> PutTopMargin( 0 );
page_setup -> PutBottomMargin( 0 );
page_setup -> PutRightMargin( 0 );
page_setup -> PutLeftMargin( 0 );
SelectionPtr selection;
selection
=
word_app
->
GetSelection();
_ParagraphFormatPtrparafmt
=
selection
->
GetParagraphFormat();
parafmt -> PutLineSpacingRule(wdLineSpaceExactly);
parafmt -> PutLineSpacing( 50 );
_FontPtrfont;
font
=
oSel
->
GetFont();
font -> PutBold( 1 );
font -> PutColor(wdColorGreen);
font -> PutSize( 20 );
font -> PutName(_T( " 宋体 " ));
selection -> TypeText( " ABC " );
oSel -> TypeParagraph();
oSel -> TypeText( " 12345678901234567890 " );
oSel
selection
_ParagraphFormatPtr
parafmt -> PutLineSpacingRule(wdLineSpaceExactly);
parafmt -> PutLineSpacing( 50 );
_FontPtr
font
font -> PutBold( 1 );
font -> PutColor(wdColorGreen);
font -> PutSize( 20 );
font -> PutName(_T( " 宋体 " ));
selection -> TypeText( " ABC " );
oSel -> TypeParagraph();
oSel -> TypeText( " 12345678901234567890 " );
oSel