vc使用com操作word

 

1.vc把文字内容存成word文件

#include <ole2.h>
  #include <stdio.h>

void ErrHandler(HRESULT hr, EXCEPINFO excep)
  {
      if(hr==DISP_E_EXCEPTION)
      {
          char  errDesc[512];
          char  errMsg[512];
          wcstombs(errDesc,  excep.bstrDescription, 512);
          sprintf(errMsg,  "Run-time error %d:\n\n %s",
                   excep.scode & 0x0000FFFF,  //Lower 16-bits of  SCODE
                   errDesc);                   //Text error description
::MessageBox(NULL, errMsg, "Server Error", MB_SETFOREGROUND |
                        MB_OK);
      }
      else
      {
          LPVOID lpMsgBuf;
           ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                           FORMAT_MESSAGE_FROM_SYSTEM |
                           FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr,
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,
                           0, NULL);
          ::MessageBox(NULL,  (LPCTSTR)lpMsgBuf, "COM Error",
                        MB_OK | MB_SETFOREGROUND);
          ::LocalFree( lpMsgBuf  );
      }

}

int main(int argc, char* argv[])
  {

    // ******************* Declare Some Variables ********************

    // Variables that will be used and re-used in our calls
      DISPPARAMS dpNoArgs = {NULL, NULL, 0,  0};
      VARIANT vResult;
      OLECHAR FAR* szFunction;
      BSTR bstrTemp;

    // IDispatch pointers for Word's objects
      IDispatch*  pDispDocs;      //Documents  collection
      IDispatch*  pDispSel;       //Selection  object
      IDispatch* pDispActiveDoc; //ActiveDocument  object

    // DISPID's
      DISPID  dispid_Docs;         //Documents property of Application object
      DISPID dispid_DocsAdd;      //Add method of Documents collection
                                  //object
      DISPID  dispid_Sel;          //Selection property of Applicaiton object
      DISPID dispid_TypeText;     //TypeText method of Selection object
      DISPID dispid_TypePara;     //TypeParagraph method of Selection object
      DISPID dispid_ActiveDoc;    //ActiveDocument property of Application
                                  //obj
      DISPID  dispid_SaveAs;      //SaveAs method of  the Document object
      DISPID  dispid_Quit;        //Quit  method of the Application object

    // ******************** Start Automation ***********************

    //Initialize the COM libraries
      ::CoInitialize(NULL);

    // Create an instance of the Word application and obtain the pointer
      // to the application's IDispatch  interface.
      CLSID clsid;
      CLSIDFromProgID(L"Word.Application",  &clsid);

    IUnknown* pUnk;
      HRESULT hr = ::CoCreateInstance( clsid, NULL,  CLSCTX_SERVER,
                                        IID_IUnknown, (void**) &pUnk);
      IDispatch* pDispApp;
      hr = pUnk->QueryInterface(IID_IDispatch,  (void**)&pDispApp);

    // Get IDispatch* for the Documents collection object
      szFunction = OLESTR("Documents");
      hr = pDispApp->GetIDsOfNames (IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT, &dispid_Docs);
      hr = pDispApp->Invoke (dispid_Docs,  IID_NULL, LOCALE_USER_DEFAULT,
                              DISPATCH_PROPERTYGET, &dpNoArgs, &vResult,
                              NULL, NULL);
      pDispDocs = vResult.pdispVal;

    // Invoke the Add method on the Documents collection object
      // to create a new document in Word
      // Note that the Add method can take up to 3  arguments, all of which
      // are optional. We are not passing it any so  we are using an empty
      // DISPPARAMS structure
      szFunction = OLESTR("Add");
      hr = pDispDocs->GetIDsOfNames(IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT, &dispid_DocsAdd);
      hr = pDispDocs->Invoke(dispid_DocsAdd,  IID_NULL, LOCALE_USER_DEFAULT,
                              DISPATCH_METHOD, &dpNoArgs, &vResult, NULL,
                              NULL);


      // Get IDispatch* for the Selection  object
      szFunction = OLESTR("Selection");
      hr = pDispApp->GetIDsOfNames (IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT, &dispid_Sel);
      hr = pDispApp->Invoke (dispid_Sel,  IID_NULL, LOCALE_USER_DEFAULT,
                              DISPATCH_PROPERTYGET, &dpNoArgs, &vResult,
                              NULL, NULL);
      pDispSel = vResult.pdispVal;


      // Get the DISPIDs of the TypeText and  TypeParagraph methods of the
      // Selection object.  We'll use these  DISPIDs multiple times.
      szFunction = OLESTR("TypeText");
      hr = pDispSel->GetIDsOfNames(IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT, &dispid_TypeText);

    szFunction = OLESTR("TypeParagraph");
      hr = pDispSel->GetIDsOfNames(IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT, &dispid_TypePara);

    // The TypeText method has and requires only one argument, a string,
      // so set up the DISPPARAMS accordingly
      VARIANT vArgsTypeText[1];
      DISPPARAMS dpTypeText;

    bstrTemp = ::SysAllocString(OLESTR("One"));
      vArgsTypeText [0].vt = VT_BSTR;
      vArgsTypeText [0].bstrVal = bstrTemp;
      dpTypeText.cArgs = 1;
      dpTypeText.cNamedArgs = 0;
      dpTypeText.rgvarg = vArgsTypeText;

    //Invoke the first TypeText and TypeParagraph pair
      hr = pDispSel->Invoke (dispid_TypeText,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpTypeText, NULL, NULL, NULL);
      hr = pDispSel->Invoke (dispid_TypePara,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpNoArgs, NULL, NULL, NULL);
      ::SysFreeString(bstrTemp);

    //Invoke the second TypeText and TypeParagraph pair
      bstrTemp =  ::SysAllocString(OLESTR("Two"));
      hr = pDispSel->Invoke (dispid_TypeText,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpTypeText, NULL, NULL, NULL);
      hr = pDispSel->Invoke (dispid_TypePara,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpNoArgs, NULL, NULL, NULL);
      ::SysFreeString(bstrTemp);

    //Invoke the third TypeText and TypeParagraph pair
      bstrTemp =  ::SysAllocString(OLESTR("Three"));
      hr = pDispSel->Invoke (dispid_TypeText,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpTypeText, NULL, NULL, NULL);
      hr = pDispSel->Invoke (dispid_TypePara,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                              &dpNoArgs, NULL, NULL, NULL);
      ::SysFreeString(bstrTemp);

    // Get IDispatch* for the ActiveDocument object
      szFunction = OLESTR("ActiveDocument");
      hr = pDispApp->GetIDsOfNames (IID_NULL,  &szFunction, 1,
                                     LOCALE_USER_DEFAULT,
                                     &dispid_ActiveDoc);
      hr = pDispApp->Invoke (dispid_ActiveDoc,  IID_NULL,
                              LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
                              &dpNoArgs, &vResult, NULL, NULL);
      pDispActiveDoc = vResult.pdispVal;

    //Set up the DISPPARAMS for the SaveAs method (11 arguments)
      VARIANT vArgsSaveAs[11];
      DISPPARAMS dpSaveAs;
      dpSaveAs.cArgs = 11;
      dpSaveAs.cNamedArgs = 0;
      dpSaveAs.rgvarg = vArgsSaveAs;

    BSTR bstrEmptyString;
      bstrEmptyString =  ::SysAllocString(OLESTR(""));

    VARIANT vFalse;
      vFalse.vt = VT_BOOL;
      vFalse.boolVal = FALSE;

    //TRY THIS:
      //To see the error handler in action, change  the following
      //line to:
      //
      //     bstrTemp =  ::SysAllocString(OLESTR("c:\\badpath\\doc1.doc"));
      bstrTemp =  ::SysAllocString(OLESTR("c:\\doc1.doc"));

    //TRY THIS:
      //To see the error handler in action, change  the following
      //line to:
      //
      //   vArgsSaveAs[10].vt =  VT_I4;       
      vArgsSaveAs[10].vt =  VT_BSTR;       
      vArgsSaveAs[10].bstrVal =  bstrTemp;         //Filename
      vArgsSaveAs[9].vt =  VT_I4;          
      vArgsSaveAs[9].lVal =  0;                    //FileFormat
      vArgsSaveAs[8] =  vFalse;                    //LockComments
      vArgsSaveAs[7].vt = VT_BSTR;
      vArgsSaveAs[7].bstrVal =  bstrEmptyString;  //Password
      vArgsSaveAs[6].vt =  VT_BOOL;    
      vArgsSaveAs[6].boolVal =  TRUE;              //AddToRecentFiles
      vArgsSaveAs[5].vt = VT_BSTR;
      vArgsSaveAs[5].bstrVal =  bstrEmptyString;  //WritePassword
      vArgsSaveAs[4] =  vFalse;                    //ReadOnlyRecommended
      vArgsSaveAs[3] =  vFalse;                    //EmbedTrueTypeFonts
      vArgsSaveAs[2] =  vFalse;                    //SaveNativePictureFormat
      vArgsSaveAs[1] =  vFalse;                    //SaveFormsData
      vArgsSaveAs[0] =  vFalse;                    //SaveAsOCELetter


      //Invoke the SaveAs method
      szFunction = OLESTR("SaveAs");
      hr =  pDispActiveDoc->GetIDsOfNames(IID_NULL, &szFunction,  1,
                                     LOCALE_USER_DEFAULT, &dispid_SaveAs);
      EXCEPINFO excep;
      hr = pDispActiveDoc->Invoke(dispid_SaveAs,  IID_NULL,
                                   LOCALE_USER_DEFAULT, DISPATCH_METHOD,
                                   &dpSaveAs, NULL, &excep, NULL);
      if (FAILED(hr))
      {
          ErrHandler(hr,  excep);
      }

    ::SysFreeString(bstrEmptyString);

    //Invoke the Quit method
      szFunction = OLESTR("Quit");
      hr = pDispApp->GetIDsOfNames(IID_NULL,  &szFunction, 1,
                                    LOCALE_USER_DEFAULT, &dispid_Quit);
      hr = pDispApp->Invoke (dispid_Quit,  IID_NULL, LOCALE_USER_DEFAULT,
                              DISPATCH_METHOD, &dpNoArgs, NULL, NULL, NULL);

    //Clean-up
      ::SysFreeString(bstrTemp);
      pDispActiveDoc->Release();
      pDispSel->Release();
      pDispDocs->Release();
      pDispApp->Release();
      pUnk->Release();

    ::CoUninitialize();

    return 0;

}

2.vc把word文件转成txt文件(好获取word文件的文字内容)

#include <ole2.h>
  #include <stdio.h>

void DocToTxt(BSTR bstrOpenFile, BSTR bstrSaveFile);
  void DocToTxt(BSTR bstrOpenFile, BSTR bstrSaveFile)
  {
      // ******************* Declare Some Variables  ********************

    // Variables that will be used and re-used in our calls
       DISPPARAMS        m_dpNoArgs =  {NULL, NULL, 0, 0};
       VARIANT             m_vResult;
      OLECHAR FAR*     m_szFunction;

    // IDispatch pointers for Word's objects
       IDispatch*         m_pDispDocs;           //Documents collection
       IDispatch*         m_pDispActiveDoc;      //ActiveDocument  object

    // DISPID's
       DISPID             m_dispid_Docs;         //Documents property of Application object
       DISPID             m_dispid_ActiveDoc;   //ActiveDocument property of  Application
       DISPID             m_dispid_SaveAs;      //SaveAs method of  the Document object
       DISPID             m_dispid_Quit;        //Quit  method of the Application object

    DISPID            m_dispid_Open;          //Open method of the Application object
       BSTR             m_bstrEmptyString ;

    // ******************** Start Automation ***********************

    //Initialize the COM libraries
      ::CoInitialize(NULL);

    // Create an instance of the Word application and obtain the pointer
      // to the application's IDispatch  interface.
      CLSID    m_clsid;
      CLSIDFromProgID(L"Word.Application",  &m_clsid);

    IUnknown*    m_pUnk;
      HRESULT m_hr = ::CoCreateInstance( m_clsid,  NULL, CLSCTX_SERVER,
                                          IID_IUnknown, (void**) &m_pUnk);
      IDispatch*    m_pDispApp;
      m_hr = m_pUnk->QueryInterface(  IID_IDispatch, (void**)&m_pDispApp);

    // Get IDispatch* for the Documents collection object
      m_szFunction = OLESTR("Documents");
      m_hr = m_pDispApp->GetIDsOfNames (IID_NULL,  &m_szFunction, 1,
                                         LOCALE_USER_DEFAULT, &m_dispid_Docs);
      m_hr = m_pDispApp->Invoke (m_dispid_Docs,  IID_NULL, LOCALE_USER_DEFAULT,
                                  DISPATCH_PROPERTYGET, &m_dpNoArgs, &m_vResult,
                                  NULL, NULL);
      m_pDispDocs = m_vResult.pdispVal;

    // Query id of method open
      m_szFunction = OLESTR("Open");
      m_hr = m_pDispDocs->GetIDsOfNames(IID_NULL,  &m_szFunction,1,
                                         LOCALE_USER_DEFAULT, &m_dispid_Open);

    // Prepare parameters for open method
       VARIANT         vArgsOpen[6];
      DISPPARAMS    dpOpen;
       dpOpen.cArgs        = 6;
      dpOpen.cNamedArgs   = 0;
       dpOpen.rgvarg        =  vArgsOpen;

    VARIANT        vFalse, vTrue;
       vFalse.vt             = VT_BOOL;
       vFalse.boolVal        =  FALSE;
       vTrue.vt             = VT_BOOL;
       vTrue.boolVal        =  TRUE;


      m_bstrEmptyString =  ::SysAllocString(OLESTR("")) ;

    vArgsOpen[5].vt            = VT_BSTR;
      vArgsOpen[5].bstrVal    =  bstrOpenFile;
       vArgsOpen[4]             = vFalse;
       vArgsOpen[3]             = vTrue;
       vArgsOpen[2]             = vFalse;
       vArgsOpen[1].vt             = VT_BSTR;
      vArgsOpen[1].bstrVal    =  m_bstrEmptyString;
       vArgsOpen[0].vt             = VT_BSTR;
      vArgsOpen[0].bstrVal    =  m_bstrEmptyString;

    //Execute open method
       m_hr=m_pDispDocs->Invoke(m_dispid_Open,IID_NULL,LOCALE_USER_DEFAULT,
                                DISPATCH_METHOD,&dpOpen,NULL,NULL,NULL);

    //Query activedocument interface
      m_szFunction = OLESTR("ActiveDocument");
      m_hr = m_pDispApp->GetIDsOfNames(IID_NULL,  &m_szFunction, 1,
                                        LOCALE_USER_DEFAULT,&m_dispid_ActiveDoc);
      m_hr =  m_pDispApp->Invoke(m_dispid_ActiveDoc,IID_NULL,
                                 LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
                                 &m_dpNoArgs,&m_vResult,NULL,NULL);
      m_pDispActiveDoc = m_vResult.pdispVal;

    //Prepare arguments for save as .txt
       VARIANT             vArgsSaveAs[11];
       DISPPARAMS         dpSaveAs;
       dpSaveAs.cArgs             =   11;
       dpSaveAs.cNamedArgs         =   0;
       dpSaveAs.rgvarg             =   vArgsSaveAs;

    vArgsSaveAs[10].vt        =   VT_BSTR;
      vArgsSaveAs[10].bstrVal =     bstrSaveFile;         //Filename
       vArgsSaveAs[9].vt         =   VT_I4;
       vArgsSaveAs[9].lVal         =    2;                   //FileFormat(wdFormatText = 2)
       vArgsSaveAs[8]             =    vFalse;                 //LockComments
       vArgsSaveAs[7].vt         =   VT_BSTR;
      vArgsSaveAs[7].bstrVal  =    m_bstrEmptyString;  //Password
       vArgsSaveAs[6].vt         =   VT_BOOL;
      vArgsSaveAs[6].boolVal  =    TRUE;                //AddToRecentFiles
       vArgsSaveAs[5].vt         =   VT_BSTR;
      vArgsSaveAs[5].bstrVal  =    m_bstrEmptyString;  //WritePassword
       vArgsSaveAs[4]             =    vFalse;              //ReadOnlyRecommended
       vArgsSaveAs[3]             =    vFalse;              //EmbedTrueTypeFonts
       vArgsSaveAs[2]             =    vFalse;              //SaveNativePictureFormat
       vArgsSaveAs[1]             =    vFalse;              //SaveFormsData
       vArgsSaveAs[0]             =    vFalse;                 //SaveAsOCELetter

    // Query and execute SaveAs method
      m_szFunction = OLESTR("SaveAs");
      m_hr =  m_pDispActiveDoc->GetIDsOfNames(IID_NULL,&m_szFunction,1,
                                              LOCALE_USER_DEFAULT,&m_dispid_SaveAs);
      m_hr =  m_pDispActiveDoc->Invoke(m_dispid_SaveAs, IID_NULL,
                                       LOCALE_USER_DEFAULT,DISPATCH_METHOD,
                                       &dpSaveAs,NULL,NULL,NULL);
      // Invoke the Quit method
      m_szFunction = OLESTR("Quit");
      m_hr = m_pDispApp->GetIDsOfNames(IID_NULL,  &m_szFunction, 1,
                                        LOCALE_USER_DEFAULT, &m_dispid_Quit);
      m_hr = m_pDispApp->Invoke(m_dispid_Quit,  IID_NULL, LOCALE_USER_DEFAULT,
                                 DISPATCH_METHOD, &m_dpNoArgs, NULL, NULL, NULL);

    //Clean-up
      ::SysFreeString(bstrOpenFile) ;
      ::SysFreeString(bstrSaveFile) ;
      ::SysFreeString(m_bstrEmptyString) ;

    m_pDispActiveDoc->Release();
      m_pDispDocs->Release();
      m_pDispApp->Release();
      m_pUnk->Release();

    ::CoUninitialize();
  }
  int main(int argc, char* argv[])
  {
      BSTR str1,str2 ;
      str1 =  ::SysAllocString(OLESTR("C:\\doc1.doc"));
      str2 =  ::SysAllocString(OLESTR("C:\\doc1.txt"));
      DocToTxt(str1,str2);
      return 0;
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值