【MFC/C++操作word】Word篇

MFC操作Word

一.初始化操作

1.导入类库

下面的操作基于Word2003

点击查看->建立类向导-> Add Class...From a type Library...-> C:Program FilesMicrosoft OfficeOfficeMSWORD9.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

[cpp] view plaincopy
 
  1. #include "msword.h"  
  2.   
  3. #define wdCharacter 1  
  4. #define wdLine 5  
  5. #define wdCell 12  
  6. #define wdExtend 1  
  7. #define wdMove 0  
  8. using namespace myword;  
  9. #include "atlbase.h"  
  10.   
  11.   
  12. class CWordOperate    
  13. {  
  14. public:  
  15.     CWordOperate();  
  16.     virtual ~CWordOperate();  
  17. private:  
  18.     _Application m_wdApp;  
  19.     Documents m_wdDocs;  
  20.     _Document m_wdDoc;  
  21.     Selection m_wdSel;  
  22.     Range     m_wdRange;  
  23.   
  24.   
  25. public:  
  26.     //操作  
  27.     //**********************创建新文档*******************************************  
  28.     BOOL CreateApp();                    //创建一个新的WORD应用程序  
  29.     BOOL CreateDocuments();                //创建一个新的Word文档集合  
  30.     BOOL CreateDocument();                //创建一个新的Word文档  
  31.     BOOL Create();                        //创建新的WORD应用程序并创建一个新的文档  
  32.     void ShowApp();                        //显示WORD文档  
  33.     void HideApp();                        //隐藏word文档  
  34.   
  35.     //**********************打开文档*********************************************  
  36.     BOOL OpenDocument(CString fileName);//打开已经存在的文档。  
  37.     BOOL Open(CString fileName);        //创建新的WORD应用程序并打开一个已经存在的文档。  
  38.     BOOL SetActiveDocument(short i);    //设置当前激活的文档。  
  39.   
  40.     //**********************保存文档*********************************************  
  41.     BOOL SaveDocument();                //文档是以打开形式,保存。  
  42.     BOOL SaveDocumentAs(CString fileName);//文档以创建形式,保存。  
  43.     BOOL CloseDocument();  
  44.     void CloseApp();   
  45.   
  46.     //**********************文本书写操作*****************************************  
  47.     void WriteText(CString szText);        //当前光标处写文本  
  48.     void WriteNewLineText(CString szText, int nLineCount = 1); //换N行写字  
  49.     void WriteEndLine(CString szText);    //文档结尾处写文本  
  50.     void WholeStory();                    //全选文档内容  
  51.     void Copy();                        //复制文本内容到剪贴板  
  52.     void InsertFile(CString fileName);    //将本地的文件全部内容写入到当前文档的光标处。  
  53.     //----------------------add by zxx--------------------------------------  
  54.     //***********************光标操作********************************************  
  55.     //上下按行选择  
  56.     void SelectMoveDown(short lineCount, short unit);//有选择操作的移动  
  57.     void NoneSelectMoveDown(short lineCount, short unit);//仅仅移动光标,不选中  
  58.     void SelectMoveUp(short lineCount, short unit);//有选择操作的移动  
  59.     void NoneSelectMoveUp(short lineCount, short unit);//仅仅移动光标,不选中  
  60.     //左右按列选择  
  61.     void SelectMoveLeft(short charCount, short unit);//有选择操作的移动  
  62.     void NoneSelectMoveLeft(short charCount, short unit);//  
  63.     void SelectMoveRight(short charCount, short unit);//有选择操作的移动  
  64.     void NoneSelectMoveRight(short charCount, short unit);//  
  65.   
  66.   
  67.     void MoveToFirst();  
  68.     void MoveToNextPage();  
  69.     void TypeParagraph();  
  70.     void PasteAndFormat();  
  71.     void Paste();  
  72.     void TypeBackspace(int count);  
  73. };  


 

WordOperate.cpp

[cpp] view plaincopy
 
  1. CWordOperate::CWordOperate()  
  2. {  
  3.   
  4. }  
  5.   
  6.   
  7. CWordOperate::~CWordOperate()  
  8. {  
  9.   
  10. }  
  11.   
  12. //操作  
  13. BOOL CWordOperate::CreateApp()  
  14. {  
  15.     COleException pe;  
  16.     if (!m_wdApp.CreateDispatch(_T("Word.Application"), &pe))  
  17.     {  
  18.         AfxMessageBox("Application创建失败,请确保安装了word 2000或以上版本!", MB_OK|MB_ICONWARNING);  
  19.         pe.ReportError();  
  20.         throw &pe;  
  21.         return FALSE;  
  22.     }  
  23.     return TRUE;  
  24. }  
  25.   
  26. BOOL CWordOperate::CreateDocuments()  
  27. {  
  28.     if (FALSE == CreateApp())   
  29.     {  
  30.         return FALSE;  
  31.     }  
  32.     m_wdDocs.AttachDispatch(m_wdApp.GetDocuments());  
  33.     if (!m_wdDocs.m_lpDispatch)   
  34.     {  
  35.         AfxMessageBox("Documents创建失败!", MB_OK|MB_ICONWARNING);  
  36.         return FALSE;  
  37.     }  
  38.     return TRUE;  
  39. }  
  40.   
  41. BOOL CWordOperate::CreateDocument()  
  42. {  
  43.     if (!m_wdDocs.m_lpDispatch)   
  44.     {  
  45.         AfxMessageBox("Documents为空!", MB_OK|MB_ICONWARNING);  
  46.         return FALSE;  
  47.     }  
  48.   
  49.     COleVariant varTrue(short(1),VT_BOOL),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  
  50.     CComVariant Template(_T(""));    //没有使用WORD的文档模板  
  51.     CComVariant NewTemplate(false),DocumentType(0),Visible;  
  52.   
  53.     m_wdDocs.Add(&Template,&NewTemplate,&DocumentType,&Visible);      
  54.   
  55.     //得到document变量  
  56.     m_wdDoc = m_wdApp.GetActiveDocument();  
  57.     if (!m_wdDoc.m_lpDispatch)   
  58.     {  
  59.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  60.         return FALSE;  
  61.     }  
  62.     //得到selection变量  
  63.     m_wdSel = m_wdApp.GetSelection();  
  64.     if (!m_wdSel.m_lpDispatch)   
  65.     {  
  66.         AfxMessageBox("Select获取失败!", MB_OK|MB_ICONWARNING);  
  67.         return FALSE;  
  68.     }  
  69.     //得到Range变量  
  70.     m_wdRange = m_wdDoc.Range(vOptional,vOptional);  
  71.     if(!m_wdRange.m_lpDispatch)  
  72.     {  
  73.         AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);  
  74.         return FALSE;  
  75.     }  
  76.   
  77.     return TRUE;  
  78. }  
  79.   
  80. BOOL CWordOperate::Create()  
  81. {  
  82.     if (FALSE == CreateDocuments())   
  83.     {  
  84.         return FALSE;  
  85.     }  
  86.     return CreateDocument();  
  87. }  
  88.   
  89. void CWordOperate::ShowApp()  
  90. {  
  91.     m_wdApp.SetVisible(TRUE);  
  92. }  
  93.   
  94. void CWordOperate::HideApp()  
  95. {  
  96.     m_wdApp.SetVisible(FALSE);  
  97. }  
  98.   
  99. BOOL CWordOperate::OpenDocument(CString fileName)  
  100. {  
  101.     if (!m_wdDocs.m_lpDispatch)   
  102.     {  
  103.         AfxMessageBox("Documents为空!", MB_OK|MB_ICONWARNING);  
  104.         return FALSE;  
  105.     }  
  106.   
  107.     COleVariant vTrue((short)TRUE),      
  108.                 vFalse((short)FALSE),  
  109.                 vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR),  
  110.                 vZ((short)0);  
  111.     COleVariant     vFileName(_T(fileName));  
  112.       
  113.     //得到document变量  
  114.     m_wdDoc.AttachDispatch(m_wdDocs.Open(  
  115.                                 vFileName,        // FileName  
  116.                                 vTrue,            // Confirm Conversion.  
  117.                                 vFalse,            // ReadOnly.  
  118.                                 vFalse,            // AddToRecentFiles.  
  119.                                 vOptional,        // PasswordDocument.  
  120.                                 vOptional,        // PasswordTemplate.  
  121.                                 vOptional,        // Revert.  
  122.                                 vOptional,        // WritePasswordDocument.  
  123.                                 vOptional,        // WritePasswordTemplate.  
  124.                                 vOptional,        // Format. // Last argument for Word 97  
  125.                                 vOptional,        // Encoding // New for Word 2000/2002  
  126.                                 vOptional,        // Visible  
  127.                                 //如下4个是word2003需要的参数。本版本是word2000。  
  128.                                 vOptional,    // OpenAndRepair  
  129.                                 vZ,            // DocumentDirection wdDocumentDirection LeftToRight  
  130.                                 vOptional,    // NoEncodingDialog  
  131.                                 vOptional  
  132.                                   
  133.                                 )                // Close Open parameters  
  134.                             );                    // Close AttachDispatch  
  135.       
  136.     if (!m_wdDoc.m_lpDispatch)   
  137.     {  
  138.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  139.         return FALSE;  
  140.     }  
  141.     //得到selection变量  
  142.     m_wdSel = m_wdApp.GetSelection();  
  143.     if (!m_wdSel.m_lpDispatch)   
  144.     {  
  145.         AfxMessageBox("Select获取失败!", MB_OK|MB_ICONWARNING);  
  146.         return FALSE;  
  147.     }  
  148.     //得到全部DOC的Range变量  
  149.     m_wdRange = m_wdDoc.Range(vOptional,vOptional);  
  150.     if(!m_wdRange.m_lpDispatch)  
  151.     {  
  152.         AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);  
  153.         return FALSE;  
  154.     }  
  155.     return TRUE;  
  156. }  
  157.   
  158. BOOL CWordOperate::Open(CString fileName)  
  159. {  
  160.     if (FALSE == CreateDocuments())   
  161.     {  
  162.         return FALSE;  
  163.     }  
  164.     //HideApp();  
  165.     return OpenDocument(fileName);  
  166. }  
  167.   
  168. BOOL CWordOperate::SetActiveDocument(short i)  
  169. {  
  170.     COleVariant     vIndex(_T(i)),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  
  171.   
  172.     m_wdDoc.AttachDispatch(m_wdDocs.Item(vIndex));  
  173.     m_wdDoc.Activate();  
  174.     if (!m_wdDoc.m_lpDispatch)   
  175.     {  
  176.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  177.         return FALSE;  
  178.     }  
  179.     //得到selection变量  
  180.     m_wdSel = m_wdApp.GetSelection();  
  181.     if (!m_wdSel.m_lpDispatch)   
  182.     {  
  183.         AfxMessageBox("Select获取失败!", MB_OK|MB_ICONWARNING);  
  184.         return FALSE;  
  185.     }  
  186.     //得到全部DOC的Range变量  
  187.     m_wdRange = m_wdDoc.Range(vOptional,vOptional);  
  188.     if(!m_wdRange.m_lpDispatch)  
  189.     {  
  190.         AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);  
  191.         return FALSE;  
  192.     }  
  193.     HideApp();  
  194.     return TRUE;  
  195. }  
  196.   
  197. BOOL CWordOperate::SaveDocument()  
  198. {  
  199.     if (!m_wdDoc.m_lpDispatch)   
  200.     {  
  201.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  202.         return FALSE;  
  203.     }  
  204.     m_wdDoc.Save();  
  205.     return TRUE;  
  206. }  
  207.   
  208. BOOL CWordOperate::SaveDocumentAs(CString fileName)  
  209. {  
  210.     if (!m_wdDoc.m_lpDispatch)   
  211.     {  
  212.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  213.         return FALSE;  
  214.     }  
  215.     COleVariant vTrue((short)TRUE),      
  216.                 vFalse((short)FALSE),  
  217.                 vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  
  218.     COleVariant vFileName(_T(fileName));  
  219.   
  220.     m_wdDoc.SaveAs(  
  221.                 vFileName,    //VARIANT* FileName  
  222.                 vOptional,    //VARIANT* FileFormat  
  223.                 vOptional,    //VARIANT* LockComments  
  224.                 vOptional,    //VARIANT* Password  
  225.                 vOptional,    //VARIANT* AddToRecentFiles  
  226.                 vOptional,    //VARIANT* WritePassword  
  227.                 vOptional,    //VARIANT* ReadOnlyRecommended  
  228.                 vOptional,    //VARIANT* EmbedTrueTypeFonts  
  229.                 vOptional,    //VARIANT* SaveNativePictureFormat  
  230.                 vOptional,    //VARIANT* SaveFormsData  
  231.                 vOptional,    //VARIANT* SaveAsAOCELetter  
  232.                 vOptional,    //VARIANT* ReadOnlyRecommended  
  233.                 vOptional,    //VARIANT* EmbedTrueTypeFonts  
  234.                 vOptional,    //VARIANT* SaveNativePictureFormat  
  235.                 vOptional,    //VARIANT* SaveFormsData  
  236.                 vOptional    //VARIANT* SaveAsAOCELetter  
  237.                 );  
  238.     return    TRUE;  
  239. }  
  240.   
  241. BOOL CWordOperate::CloseDocument()  
  242. {  
  243.     COleVariant vTrue((short)TRUE),      
  244.                 vFalse((short)FALSE),  
  245.                 vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  
  246.       
  247.     m_wdDoc.Close(vFalse,    // SaveChanges.  
  248.              vTrue,            // OriginalFormat.  
  249.              vFalse            // RouteDocument.  
  250.              );  
  251.     //AfxMessageBox("c1");  
  252.     m_wdDoc.AttachDispatch(m_wdApp.GetActiveDocument());  
  253.     if (!m_wdDoc.m_lpDispatch)   
  254.     {  
  255.         AfxMessageBox("Document获取失败!", MB_OK|MB_ICONWARNING);  
  256.         return FALSE;  
  257.     }  
  258. //  AfxMessageBox("c2");  
  259.     //得到selection变量  
  260.     m_wdSel = m_wdApp.GetSelection();  
  261.     if (!m_wdSel.m_lpDispatch)   
  262.     {  
  263.         AfxMessageBox("Select获取失败!", MB_OK|MB_ICONWARNING);  
  264.         return FALSE;  
  265.     }  
  266. //  AfxMessageBox("c3");  
  267.     //得到全部DOC的Range变量  
  268.     m_wdRange = m_wdDoc.Range(vOptional,vOptional);  
  269.     if(!m_wdRange.m_lpDispatch)  
  270.     {  
  271.         AfxMessageBox("Range获取失败!", MB_OK|MB_ICONWARNING);  
  272.         return FALSE;  
  273.     }  
  274. //  AfxMessageBox("c4");  
  275.     return TRUE;  
  276. }  
  277.   
  278. void CWordOperate::CloseApp()  
  279. {  
  280.     COleVariant vTrue((short)TRUE),      
  281.                 vFalse((short)FALSE),  
  282.                 vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);  
  283.     m_wdDoc.Save();  
  284.     m_wdApp.Quit(vFalse,    // SaveChanges.  
  285.              vTrue,            // OriginalFormat.  
  286.              vFalse            // RouteDocument.  
  287.              );  
  288.     //释放内存申请资源  
  289.   
  290.     m_wdRange.ReleaseDispatch();  
  291.     m_wdSel.ReleaseDispatch();  
  292.     m_wdDoc.ReleaseDispatch();  
  293.     m_wdDocs.ReleaseDispatch();  
  294.     m_wdApp.ReleaseDispatch();  
  295. }  
  296.   
  297. void CWordOperate::WriteText(CString szText)  
  298. {  
  299.     m_wdSel.TypeText(szText);  
  300. }  
  301.   
  302. void CWordOperate::WriteNewLineText(CString szText, int nLineCount /**//* = 1 */)  
  303. {  
  304.     int i;  
  305.     if (nLineCount <= 0)  
  306.     {  
  307.         nLineCount = 0;  
  308.     }  
  309.     for (i = 0; i < nLineCount; i++)  
  310.     {  
  311.         m_wdSel.TypeParagraph();  
  312.     }  
  313.     WriteText(szText);  
  314. }  
  315.   
  316. void CWordOperate::WriteEndLine(CString szText)  
  317. {  
  318.     m_wdRange.InsertAfter(szText);  
  319. }  
  320.   
  321. void CWordOperate::WholeStory()  
  322. {  
  323.     m_wdRange.WholeStory();  
  324. }  
  325.   
  326. void CWordOperate::Copy()  
  327. {  
  328.     m_wdSel.Copy();  
  329.     //m_wdSel.CopyFormat();  
  330. }  
  331.   
  332. void CWordOperate::TypeParagraph()  
  333. {  
  334.     m_wdSel.TypeParagraph();  
  335. }  
  336.   
  337. void CWordOperate::PasteAndFormat()  
  338. {  
  339.     m_wdSel.PasteAndFormat(0);  
  340. }  
  341.   
  342. void CWordOperate::Paste()  
  343. {  
  344.     m_wdSel.Paste();  
  345.     //m_wdSel.PasteFormat();  
  346. }  
  347.   
  348. void CWordOperate::TypeBackspace(int count)  
  349. {  
  350.    for(int i = 0; i < count; i++)  
  351.    m_wdSel.TypeBackspace();  
  352. }  
[cpp] view plaincopy
 
  1.    
[cpp] view plaincopy
 
  1. void CWordOperate::InsertFile(CString fileName)  
  2. {  
  3.     COleVariant     vFileName(fileName),  
  4.                  vTrue((short)TRUE),  
  5.                  vFalse((short)FALSE),  
  6.                  vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR),  
  7.                  vNull(_T(""));  
  8.     /**//* 
  9.     void InsertFile(LPCTSTR FileName, VARIANT* Range, VARIANT* ConfirmConversions, VARIANT* Link, VARIANT* Attachment); 
  10.     */  
  11.     m_wdSel.InsertFile(  
  12.                     fileName,  
  13.                     vNull,  
  14.                     vFalse,  
  15.                     vFalse,  
  16.                     vFalse  
  17.                     );  
  18. }  
  19.   
  20. void CWordOperate::SelectMoveDown(short lineCount, short unit)//有选择操作的移动  
  21. {  
  22.     m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend));  
  23. }  
  24.   
  25. void CWordOperate::NoneSelectMoveDown(short lineCount, short unit)//仅仅移动光标,不选中  
  26. {  
  27.     m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove));  
  28. }  
  29.   
  30. void CWordOperate::SelectMoveUp(short lineCount, short unit)//有选择操作的移动  
  31. {  
  32.     m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend));  
  33. }  
  34.   
  35. void CWordOperate::NoneSelectMoveUp(short lineCount, short unit)//仅仅移动光标,不选中  
  36. {  
  37.     m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove));  
  38. }  
  39.   
  40. void CWordOperate::SelectMoveLeft(short charCount, short unit)//有选择操作的移动  
  41. {  
  42.     m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend));  
  43. }  
  44.   
  45. void CWordOperate::NoneSelectMoveLeft(short charCount, short unit)//  
  46. {  
  47.     m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove));  
  48. }  
  49. void CWordOperate::SelectMoveRight(short charCount, short unit)//有选择操作的移动  
  50. {  
  51.     m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend));  
  52. }  
  53. void CWordOperate::NoneSelectMoveRight(short charCount, short unit)//  
  54. {  
  55.     m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove));  
  56. }  
  57. void CWordOperate::MoveToFirst()  
  58. {  
  59.     m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)0), COleVariant("1"));  
  60. }  
  61.   
  62. void CWordOperate::MoveToNextPage()  
  63. {  
  64.     m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)1), COleVariant(""));  
  65. }  


 

三.可能遇到的问题

1.问题:CreateDispatch 没有注册类别

   解答:使用静态编译即可。

原文地址:https://www.cnblogs.com/For-her/p/3499779.html