vc操作word的简单例子

时间:2022-03-03 06:21:14
void CMyDialog::OnBnClickedOk()
{



if(IDOK!=AfxMessageBox(_T("看好了,就要新建一个文档了")))
return;



CApplication app;
app.CreateDispatch(_T("Word.Application"));
app.put_Visible(TRUE);



CDocuments docs=app.get_Documents();


CComVariant Template(_T("")); //为了简单,没有使用WORD的文档模板
CComVariant NewTemplate(false),DocumentType(0),Visible;
docs.Add(&Template,&NewTemplate,&DocumentType,&Visible);


CSelection sel=app.get_Selection();

sel.TypeText(_T("我是被写入的句子!"));




CDocument0 doc=app.get_ActiveDocument(); //得到ActiveDocument
CComVariant FileName(_T("c:\\Hello.doc")); //文件名
CComVariant FileFormat(0); //重点,看下面的说明
CComVariant LockComments(false),Password(_T(""));
CComVariant AddToRecentFiles(true),WritePassword(_T(""));
CComVariant ReadOnlyRecommended(true),EmbedTrueTypeFonts(false);
CComVariant SaveNativePictureFormat(false),SaveFormsData(false);
CComVariant SaveAsAOCELetter(false);
 


CComVariant Encoding(msoEncodingUSASCII);
CComVariant InsertLineBreaks(false);
CComVariant AllowSubstitutions(false);
CComVariant LineEnding(wdCRLF );
CComVariant AddBiDiMarks(false );


 
/*doc.SaveAs( &FileName, &FileFormat, &LockComments, &Password, \
  &AddToRecentFiles, &WritePassword, &ReadOnlyRecommended, \
  &EmbedTrueTypeFonts, &SaveNativePictureFormat,&SaveFormsData,\
 &SaveAsAOCELetter, &Encoding, &InsertLineBreaks, &AllowSubstitutions, \
  &LineEnding,&AddBiDiMarks);

*/


COleVariant opt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);


doc.SaveAs( &FileName, &FileFormat,opt , opt,\
opt, opt,opt , \
opt, opt,opt,\
opt, opt,opt ,opt, \
opt,opt);




sel.ReleaseDispatch();
doc.ReleaseDispatch();
docs.ReleaseDispatch();


CComVariant SaveChanges(false),OriginalFormat,RouteDocument;


app.Quit(&SaveChanges,&OriginalFormat,&RouteDocument);



}