1. create a new console program in VC and select to support MFC (of course, you can also choose not to support MFC, but it will be very troublesome) 2. press Ctrl + W to bring up the MFC classwizard, add class-> from a type library, and select your word Type Library (for example, my name is word2003 and it is installed on the E disk, my path is "E: \ edittools \ Microsoft Office \ office11 \ MSWord. olb "), select the packaging class to be generated by classwizard in the pop-up window. In this example, the class _ application, documents, _ document, and range are used, select them and press OK
3. enter the CPP file where your main function is located, and add the header file reference # include "MSWord. H "// reference the idispatch package class generated by classwizard. 4. add code # include "stdafx. H "# include" readdoc. H "# include" MSWord. H "using namespace STD; int _ tmain (INT argc, tchar * argv [], tchar * envp []) {int nretcode = 0; If (! Afxwininit (: getmodulehandle (null ),
Null,: getcommandline (), 0) {cerr <_ T ("Fatal error: MFC initialization failed") <Endl; nretcode = 1 ;} else {If (coinitialize (null )! = S_ OK) {afxmessagebox ("failed to initialize the com support library! "); Return-1;} afxmessagebox (" the com support library is initialized successfully! "); _ Application wordapp;
Documents docs; _ document DOC; range arange; colevariant vtrue (short) True), vfalse (short) False), vopt (long) disp_e_paramnotfound, vt_error ); // wordapp. createdispatch ("word. application ", null); wordapp. createdispatch (_ T ("word. application "); wordapp. setvisible (false );
Docs = wordapp. getdocuments (); Doc = docs. open (colevariant ("D: \ txt.doc"), vfalse, vtrue, vfalse, vopt, vopt, vopt); arange = Doc. range (vopt, vopt); afxmessagebox (arange. gettext (); // gettext obtains the plain text of the Word file. You can write it to the TXT file.
Doc. Close (vopt, vopt, vopt); wordapp. Quit (vopt, vopt, vopt); couninitialize () ;}return nretcode ;}