【MFC/C++操作word】Word篇
阿新 • • 發佈:2019-02-08
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("
return FALSE;
}
二.我自己寫的Word操作類
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 沒有註冊類別
解答:使用靜態編譯即可。