MFC操作Word
一.初始化操作
1.導入類庫
下面的操作基於Word2003
點擊查看->建立類向導-> Add Class...\From a type Library...-> C:\Program Files\Microsoft Office\Office\MSWORD9.OLB,接下來就可以看到導入的類msword.h, msword.cpp。
2.初始化COM
找到App的InitInstance()函數,在其中添加 AfxOleInit()函數的調用,如:
if (!AfxOleInit())
{
AfxMessageBox("注冊COM出錯!");
return FALSE;
}
二.我自己寫的Word操作類
你寫的時候可以直接使用這個類,在它的基礎上修改一下。我參考自http://www.cnitblog.com/lifw/articles/vcpp_officeword.html,對其進行了改編:
WordOperate.h
#include "msword.h" #define wdCharacter 1 #define wdLine 5 #define wdCell 12 #define wdExtend 1 #define wdMove 0 using namespace myword; #include "atlbase.h" class CWordOperate { public: CWordOperate(); virtual ~CWordOperate(); private: _Application m_wdApp; Documents m_wdDocs; _Document m_wdDoc; Selection m_wdSel; Range m_wdRange; public: //操作 //**********************創建新文檔******************************************* BOOL CreateApp(); //創建一個新的WORD應用程序 BOOL CreateDocuments(); //創建一個新的Word文檔集合 BOOL CreateDocument(); //創建一個新的Word文檔 BOOL Create(); //創建新的WORD應用程序並創建一個新的文檔 void ShowApp(); //顯示WORD文檔 void HideApp(); //隱藏word文檔 //**********************打開文檔********************************************* BOOL OpenDocument(CString fileName);//打開已經存在的文檔。 BOOL Open(CString fileName); //創建新的WORD應用程序並打開一個已經存在的文檔。 BOOL SetActiveDocument(short i); //設置當前激活的文檔。 //**********************保存文檔********************************************* BOOL SaveDocument(); //文檔是以打開形式,保存。 BOOL SaveDocumentAs(CString fileName);//文檔以創建形式,保存。 BOOL CloseDocument(); void CloseApp(); //**********************文本書寫操作***************************************** void WriteText(CString szText); //當前光標處寫文本 void WriteNewLineText(CString szText, int nLineCount = 1); //換N行寫字 void WriteEndLine(CString szText); //文檔結尾處寫文本 void WholeStory(); //全選文檔內容 void Copy(); //復制文本內容到剪貼板 void InsertFile(CString fileName); //將本地的文件全部內容寫入到當前文檔的光標處。 //----------------------add by zxx-------------------------------------- //***********************光標操作******************************************** //上下按行選擇 void SelectMoveDown(short lineCount, short unit);//有選擇操作的移動 void NoneSelectMoveDown(short lineCount, short unit);//僅僅移動光標,不選中 void SelectMoveUp(short lineCount, short unit);//有選擇操作的移動 void NoneSelectMoveUp(short lineCount, short unit);//僅僅移動光標,不選中 //左右按列選擇 void SelectMoveLeft(short charCount, short unit);//有選擇操作的移動 void NoneSelectMoveLeft(short charCount, short unit);// void SelectMoveRight(short charCount, short unit);//有選擇操作的移動 void NoneSelectMoveRight(short charCount, short unit);// void MoveToFirst(); void MoveToNextPage(); void TypeParagraph(); void PasteAndFormat(); void Paste(); void TypeBackspace(int count); };
WordOperate.cpp
CWordOperate::CWordOperate() { } CWordOperate::~CWordOperate() { } //操作 BOOL CWordOperate::CreateApp() { COleException pe; if (!m_wdApp.CreateDispatch(_T("Word.Application"), &pe)) { AfxMessageBox("Application創建失敗,請確保安裝了word 2000或以上版本!", MB_OK|MB_ICONWARNING); pe.ReportError(); throw &pe; return FALSE; } return TRUE; } BOOL CWordOperate::CreateDocuments() { if (FALSE == CreateApp()) { return FALSE; } m_wdDocs.AttachDispatch(m_wdApp.GetDocuments()); if (!m_wdDocs.m_lpDispatch) { AfxMessageBox("Documents創建失敗!", MB_OK|MB_ICONWARNING); return FALSE; } return TRUE; } BOOL CWordOperate::CreateDocument() { if (!m_wdDocs.m_lpDispatch) { AfxMessageBox("Documents為空!", MB_OK|MB_ICONWARNING); return FALSE; } COleVariant varTrue(short(1),VT_BOOL),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); CComVariant Template(_T("")); //沒有使用WORD的文檔模板 CComVariant NewTemplate(false),DocumentType(0),Visible; m_wdDocs.Add(&Template,&NewTemplate,&DocumentType,&Visible); //得到document變量 m_wdDoc = m_wdApp.GetActiveDocument(); if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到selection變量 m_wdSel = m_wdApp.GetSelection(); if (!m_wdSel.m_lpDispatch) { AfxMessageBox("Select獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到Range變量 m_wdRange = m_wdDoc.Range(vOptional,vOptional); if(!m_wdRange.m_lpDispatch) { AfxMessageBox("Range獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } return TRUE; } BOOL CWordOperate::Create() { if (FALSE == CreateDocuments()) { return FALSE; } return CreateDocument(); } void CWordOperate::ShowApp() { m_wdApp.SetVisible(TRUE); } void CWordOperate::HideApp() { m_wdApp.SetVisible(FALSE); } BOOL CWordOperate::OpenDocument(CString fileName) { if (!m_wdDocs.m_lpDispatch) { AfxMessageBox("Documents為空!", MB_OK|MB_ICONWARNING); return FALSE; } COleVariant vTrue((short)TRUE), vFalse((short)FALSE), vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR), vZ((short)0); COleVariant vFileName(_T(fileName)); //得到document變量 m_wdDoc.AttachDispatch(m_wdDocs.Open( vFileName, // FileName vTrue, // Confirm Conversion. vFalse, // ReadOnly. vFalse, // AddToRecentFiles. vOptional, // PasswordDocument. vOptional, // PasswordTemplate. vOptional, // Revert. vOptional, // WritePasswordDocument. vOptional, // WritePasswordTemplate. vOptional, // Format. // Last argument for Word 97 vOptional, // Encoding // New for Word 2000/2002 vOptional, // Visible //如下4個是word2003需要的參數。本版本是word2000。 vOptional, // OpenAndRepair vZ, // DocumentDirection wdDocumentDirection LeftToRight vOptional, // NoEncodingDialog vOptional ) // Close Open parameters ); // Close AttachDispatch if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到selection變量 m_wdSel = m_wdApp.GetSelection(); if (!m_wdSel.m_lpDispatch) { AfxMessageBox("Select獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到全部DOC的Range變量 m_wdRange = m_wdDoc.Range(vOptional,vOptional); if(!m_wdRange.m_lpDispatch) { AfxMessageBox("Range獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } return TRUE; } BOOL CWordOperate::Open(CString fileName) { if (FALSE == CreateDocuments()) { return FALSE; } //HideApp(); return OpenDocument(fileName); } BOOL CWordOperate::SetActiveDocument(short i) { COleVariant vIndex(_T(i)),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_wdDoc.AttachDispatch(m_wdDocs.Item(vIndex)); m_wdDoc.Activate(); if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到selection變量 m_wdSel = m_wdApp.GetSelection(); if (!m_wdSel.m_lpDispatch) { AfxMessageBox("Select獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } //得到全部DOC的Range變量 m_wdRange = m_wdDoc.Range(vOptional,vOptional); if(!m_wdRange.m_lpDispatch) { AfxMessageBox("Range獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } HideApp(); return TRUE; } BOOL CWordOperate::SaveDocument() { if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } m_wdDoc.Save(); return TRUE; } BOOL CWordOperate::SaveDocumentAs(CString fileName) { if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } COleVariant vTrue((short)TRUE), vFalse((short)FALSE), vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); COleVariant vFileName(_T(fileName)); m_wdDoc.SaveAs( vFileName, //VARIANT* FileName vOptional, //VARIANT* FileFormat vOptional, //VARIANT* LockComments vOptional, //VARIANT* Password vOptional, //VARIANT* AddToRecentFiles vOptional, //VARIANT* WritePassword vOptional, //VARIANT* ReadOnlyRecommended vOptional, //VARIANT* EmbedTrueTypeFonts vOptional, //VARIANT* SaveNativePictureFormat vOptional, //VARIANT* SaveFormsData vOptional, //VARIANT* SaveAsAOCELetter vOptional, //VARIANT* ReadOnlyRecommended vOptional, //VARIANT* EmbedTrueTypeFonts vOptional, //VARIANT* SaveNativePictureFormat vOptional, //VARIANT* SaveFormsData vOptional //VARIANT* SaveAsAOCELetter ); return TRUE; } BOOL CWordOperate::CloseDocument() { COleVariant vTrue((short)TRUE), vFalse((short)FALSE), vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_wdDoc.Close(vFalse, // SaveChanges. vTrue, // OriginalFormat. vFalse // RouteDocument. ); //AfxMessageBox("c1"); m_wdDoc.AttachDispatch(m_wdApp.GetActiveDocument()); if (!m_wdDoc.m_lpDispatch) { AfxMessageBox("Document獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } // AfxMessageBox("c2"); //得到selection變量 m_wdSel = m_wdApp.GetSelection(); if (!m_wdSel.m_lpDispatch) { AfxMessageBox("Select獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } // AfxMessageBox("c3"); //得到全部DOC的Range變量 m_wdRange = m_wdDoc.Range(vOptional,vOptional); if(!m_wdRange.m_lpDispatch) { AfxMessageBox("Range獲取失敗!", MB_OK|MB_ICONWARNING); return FALSE; } // AfxMessageBox("c4"); return TRUE; } void CWordOperate::CloseApp() { COleVariant vTrue((short)TRUE), vFalse((short)FALSE), vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_wdDoc.Save(); m_wdApp.Quit(vFalse, // SaveChanges. vTrue, // OriginalFormat. vFalse // RouteDocument. ); //釋放內存申請資源 m_wdRange.ReleaseDispatch(); m_wdSel.ReleaseDispatch(); m_wdDoc.ReleaseDispatch(); m_wdDocs.ReleaseDispatch(); m_wdApp.ReleaseDispatch(); } void CWordOperate::WriteText(CString szText) { m_wdSel.TypeText(szText); } void CWordOperate::WriteNewLineText(CString szText, int nLineCount /**//* = 1 */) { int i; if (nLineCount <= 0) { nLineCount = 0; } for (i = 0; i < nLineCount; i++) { m_wdSel.TypeParagraph(); } WriteText(szText); } void CWordOperate::WriteEndLine(CString szText) { m_wdRange.InsertAfter(szText); } void CWordOperate::WholeStory() { m_wdRange.WholeStory(); } void CWordOperate::Copy() { m_wdSel.Copy(); //m_wdSel.CopyFormat(); } void CWordOperate::TypeParagraph() { m_wdSel.TypeParagraph(); } void CWordOperate::PasteAndFormat() { m_wdSel.PasteAndFormat(0); } void CWordOperate::Paste() { m_wdSel.Paste(); //m_wdSel.PasteFormat(); } void CWordOperate::TypeBackspace(int count) { for(int i = 0; i < count; i++) m_wdSel.TypeBackspace(); }
void CWordOperate::InsertFile(CString fileName) { COleVariant vFileName(fileName), vTrue((short)TRUE), vFalse((short)FALSE), vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR), vNull(_T("")); /**//* void InsertFile(LPCTSTR FileName, VARIANT* Range, VARIANT* ConfirmConversions, VARIANT* Link, VARIANT* Attachment); */ m_wdSel.InsertFile( fileName, vNull, vFalse, vFalse, vFalse ); } void CWordOperate::SelectMoveDown(short lineCount, short unit)//有選擇操作的移動 { m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend)); } void CWordOperate::NoneSelectMoveDown(short lineCount, short unit)//僅僅移動光標,不選中 { m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove)); } void CWordOperate::SelectMoveUp(short lineCount, short unit)//有選擇操作的移動 { m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend)); } void CWordOperate::NoneSelectMoveUp(short lineCount, short unit)//僅僅移動光標,不選中 { m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove)); } void CWordOperate::SelectMoveLeft(short charCount, short unit)//有選擇操作的移動 { m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend)); } void CWordOperate::NoneSelectMoveLeft(short charCount, short unit)// { m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove)); } void CWordOperate::SelectMoveRight(short charCount, short unit)//有選擇操作的移動 { m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend)); } void CWordOperate::NoneSelectMoveRight(short charCount, short unit)// { m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove)); } void CWordOperate::MoveToFirst() { m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)0), COleVariant("1")); } void CWordOperate::MoveToNextPage() { m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)1), COleVariant("")); }
三.可能遇到的問題
1.問題:CreateDispatch 沒有注冊類別
解答:使用靜態編譯即可