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

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

[cpp]view plaincopy

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

WordOperate.cpp

[cpp]view plaincopy

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

[cpp]view plaincopy

    [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. void CWordOperate::SelectMoveDown(short lineCount, short unit)//有选择操作的移动
    20. {
    21. m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend));
    22. }
    23. void CWordOperate::NoneSelectMoveDown(short lineCount, short unit)//仅仅移动光标,不选中
    24. {
    25. m_wdSel.MoveDown(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove));
    26. }
    27. void CWordOperate::SelectMoveUp(short lineCount, short unit)//有选择操作的移动
    28. {
    29. m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdExtend));
    30. }
    31. void CWordOperate::NoneSelectMoveUp(short lineCount, short unit)//仅仅移动光标,不选中
    32. {
    33. m_wdSel.MoveUp(COleVariant(unit), COleVariant((short)lineCount),COleVariant((short)wdMove));
    34. }
    35. void CWordOperate::SelectMoveLeft(short charCount, short unit)//有选择操作的移动
    36. {
    37. m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend));
    38. }
    39. void CWordOperate::NoneSelectMoveLeft(short charCount, short unit)//
    40. {
    41. m_wdSel.MoveLeft(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove));
    42. }
    43. void CWordOperate::SelectMoveRight(short charCount, short unit)//有选择操作的移动
    44. {
    45. m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdExtend));
    46. }
    47. void CWordOperate::NoneSelectMoveRight(short charCount, short unit)//
    48. {
    49. m_wdSel.MoveRight(COleVariant(unit), COleVariant((short)charCount),COleVariant((short)wdMove));
    50. }
    51. void CWordOperate::MoveToFirst()
    52. {
    53. m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)0), COleVariant("1"));
    54. }
    55. void CWordOperate::MoveToNextPage()
    56. {
    57. m_wdSel.GoTo(COleVariant((short)1), COleVariant((short)2), COleVariant((short)1), COleVariant(""));
    58. }

    三.可能遇到的问题

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

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