.h文件,需要先包含头文件,头文件见附件
#include "msword9.h"
#include "CTables0.h"
#include "CnlineShapes.h"
#include "CnlineShape.h"
#include "CPageSetup.h"
#include "CFont0.h"
#include "CParagraphFormat.h"
.cpp文件
void XXXDlg::OnBnClickedBtn()
{
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
_Application oWordApp; //开始一个新的Microsoft Word 2000实例
if (!oWordApp.CreateDispatch(_T("Word.Application"), NULL)) {
AfxMessageBox(_T("服务创建失败,请确定已经安装了Office 2000或以上版本."), MB_OK | MB_SETFOREGROUND);
return;
}
Documents oDocs; //创建一个新的word文档
_Document oDoc;
oDocs = oWordApp.GetDocuments();
oDoc = oDocs.Add(vOpt, vOpt, vOpt, vOpt); //如果是word 98,则应该带两个参数,如oDocs.Add(vOpt, vOpt)
//==============================设置页面==============================================
_Document curDoc = oWordApp.GetActiveDocument();
CPageSetup p = curDoc.GetPageSetup();
p.put_LeftMargin(30);
p.put_RightMargin(30);
p.put_TopMargin(50);
p.put_BottomMargin(40);
Selection oSel; //把文本添加到word文档
oSel = oWordApp.GetSelection();
CFont0 f = oSel.GetFont();//设置字体
oSel.BoldRun();
CParagraphFormat format = oSel.GetParagraphFormat();
format.put_Alignment(1);//设置段落格式居中
f.put_Size(25);
oSel.TypeText(_T("XXXXXXXXXX"));
oSel.TypeParagraph();//换行
oSel.TypeParagraph();
CParagraphFormat format2 = oSel.GetParagraphFormat();
format2.put_Alignment(3);//设置段落格式左对齐
oSel.TypeParagraph();
f.put_Size(18);
COleDateTime dt = COleDateTime::GetCurrentTime();
CString strDT = dt.Format(_T("%Y-%m-%d"));
CString str(_T("XXX"));
str = usernameTrans + str;
CString str2 = _T("XXXX")+tempSub+_T("XXXXXX");
str += strDT + str2;
oSel.TypeText(str);
oSel.TypeParagraph();
oSel.TypeText(_T("XXXXXX:")+tempClass);
oSel.TypeParagraph();
CParagraphFormat format3 = oSel.GetParagraphFormat();
format3.put_Alignment(2);//设置段落格式右对齐
oSel.TypeParagraph();
oSel.TypeText(_T("XXXXXXX"));
oSel.TypeParagraph();
//oSel.TypeParagraph();
//oSel.(23,25,56);
oSel.MoveRight(COleVariant((short)2), COleVariant((short)2), COleVariant((short)2));
oSel.TypeText(_T("XXXXXX"));
oSel.TypeParagraph();
oSel.TypeText(strDT);
oSel.TypeParagraph();
COleVariant vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
CnlineShapes IShapes = oSel.GetInlineShapes();
CnlineShape IShape;
oSel.MoveDown(COleVariant((short)4), COleVariant((short)1), COleVariant((short)0));
//保存word文档
_Document oActiveDoc;
oActiveDoc = oWordApp.GetActiveDocument();
oActiveDoc.SaveAs(COleVariant((_T("C:\\report\\") + strDT + tempSub+ _T(".doc"))), COleVariant((short)0), vFalse, COleVariant(_T("")), vTrue, COleVariant(_T("")), vFalse, vFalse, vFalse, vFalse, vFalse);
oSel.ReleaseDispatch();
oDoc.ReleaseDispatch();
oDocs.ReleaseDispatch();
oWordApp.SetVisible(true);//生成word之后打开word
//oWordApp.Quit(vOpt, vOpt, vOpt); //退出word应用程序
oWordApp.ReleaseDispatch();
}
大概就是这种效果
附件:MFC操作word文档所需文件
提取码:tp3p