VC operation word

Source: Internet
Author: User

Recently, based on the project requirements, I need to use vc ++ 6.0 as an ActiveX web component. I have never touched on this programming. This is the first time! So I did it, but it was a lot faster than I expected. Now, we will post the key code parts of vc ++ 6.0's word operations and share them with you.

Because I encountered many problems during development, and there was very little information on the Internet, it was basically the most basic operation. Therefore, we hope that we can avoid any detours in the development process!

Tool: vc ++ 6.0.

Keywords: c ++, MFC.

Requirement: system installation ms office 2000.

Process:

Preparations:

1. Create an MFC (EXE) project: MFC AppWizard (exe). The project is in the form of a dialog box (for testing ).

2. Create a CLASS on the Class VIEW page: Class Name: CWordOffice, CLASS type: Class type: Generic Class.

3. in the toolbar, find view> class wizard> Automation> add class> from a tye library, select MSWORD9.OLB in the directory installed by offfice, and select all the listed class names, click OK.

After the preparation is complete, the following code is provided:

The code written manually in CWordOffice. h is as follows (automatically generated is not included ):

# Include "atlbase. h"

# Include "msword9.h"

Class CWordOffice

{

Private:

_ Application m_wdApp;

Documents m_wdDocs;

_ Document m_wdDoc;

Selection m_wdSel;

Range m_wdRange;

InlineShapes m_wdInlineShapes;

InlineShape m_wdInlineShape;

Public:

CWordOffice ();

Virtual ~ CWordOffice ();

Public:

// Operation

// *********************** Create a new document ************* ******************************

BOOL CreateApp (); // create a new WORD Application

BOOL CreateDocuments (); // creates a collection of Word documents.

BOOL CreateDocument (); // create a new word document

BOOL Create (); // Create a new WORD application and a new document

Void ShowApp (); // display Word documents

Void HideApp (); // hide a Word document

// *********************** Open the document ************** *******************************

BOOL OpenDocument (CString fileName); // open an existing document.

BOOL Open (CString fileName); // create a new WORD application and Open an existing document.

BOOL SetActiveDocument (short I); // sets the currently active document.

// ********************** Save the document ************** *******************************

BOOL SaveDocument (); // The document is opened and saved.

BOOL SaveDocumentAs (CString fileName); // the document is created and saved.

BOOL CloseDocument ();

Void CloseApp ();

************* ****************************

Void WriteText (CString szText); // write the text at the current cursor

Void WriteNewLineText (CString szText, int nLineCount = 1); // change N lines

Void WriteEndLine (CString szText); // write the text at the end of the document

Void WholeStory (); // select all documents

Void Copy (); // Copy the text content to the clipboard.

Void InsertFile (CString fileName); // write all the content of the local file to the cursor of the current file.

************* ****************************

Void InsertShapes (CString fileName); // insert an image at the current cursor position

************* ****************************

Void InsertHyperlink (CString fileLink); // The hyperlink address, which can be a relative path.

};

The handwriting code in CWordOffice. c is as follows:

CWordOffice: CWordOffice ()

{

}

CWordOffice ::~ CWordOffice ()

{

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.

);

// Release the memory to apply for resources

M_wdInlineShape.ReleaseDispatch ();

M_wdInlineShapes.ReleaseDispatch ();

// M_wdTb.ReleaseDispatch ();

M_wdRange.ReleaseDispatch ();

M_wdSel.ReleaseDispatch ();

// M_wdFt.ReleaseDispatch ();

M_wdDoc.ReleaseDispatch ();

M_wdDocs.ReleaseDispatch ();

M_wdApp.ReleaseDispatch ();

}

// Operation

BOOL CWordOffice: CreateApp ()

{

If (FALSE = m_wdApp.CreateDispatch ("Word. Application "))

{

AfxMessageBox ("Application creation failed. Please make sure word 2000 or later is installed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

Return TRUE;

}

BOOL CWordOffice: CreateDocuments ()

{

If (FALSE = CreateApp ())

{

Return FALSE;

}

M_wdDocs.AttachDispatch (m_wdApp.GetDocuments ());

If (! M_wdDocs.m_lpDispatch)

{

AfxMessageBox ("Creation of Documents failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

Return true;

}

Bool cwordoffice: createdocument ()

{

If (! M_wddocs.m_lpdispatch)

{

Afxmessagebox ("documents is blank !", Mb_ OK | mb_iconwarning );

Return false;

}

Colevariant vartrue (short (1), vt_bool), voptional (long) disp_e_paramnotfound, vt_error );

Ccomvariant template (_ T (""); // The document template of the word is not used.

Ccomvariant newtemplate (false), documenttype (0), visible;

M_wddocs.add (& template, & newtemplate, & documenttype, & visible );

// Get the document variable

M_wddoc = m_wdapp.getactivedocument ();

If (! M_wddoc.m_lpdispatch)

{

Afxmessagebox ("Document Acquisition failed !", Mb_ OK | mb_iconwarning );

Return false;

}

// Obtain the selection variable

M_wdsel = m_wdapp.getselection ();

If (! M_wdsel.m_lpdispatch)

{

Afxmessagebox ("An error occurred while obtaining select !", Mb_ OK | mb_iconwarning );

Return false;

}

// Obtain the range variable.

M_wdrange = m_wddoc.range (voptional, voptional );

If (! M_wdrange.m_lpdispatch)

{

Afxmessagebox ("range acquisition failed !", Mb_ OK | mb_iconwarning );

Return false;

}

Return true;

}

Bool cwordoffice: Create ()

{

If (false = createdocuments ())

{

Return false;

}

Return createdocument ();

}

Void cwordoffice: showapp ()

{

M_wdApp.SetVisible (TRUE );

}

Void CWordOffice: HideApp ()

{

M_wdApp.SetVisible (FALSE );

}

BOOL CWordOffice: OpenDocument (CString fileName)

{

If (! M_wdDocs.m_lpDispatch)

{

AfxMessageBox ("Documents is blank !", 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 ));

// Get the document variable

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

/** // * The following four parameters are required by word2003. The current version is word2000.

// VOptional, // OpenAndRepair

// VZ, // DocumentDirection wdDocumentDirection LeftToRight

// VOptional, // NoEncodingDialog

// VOptional

*/

) // Close Open parameters

); // Close AttachDispatch

If (! M_wdDoc.m_lpDispatch)

{

AfxMessageBox ("Document Acquisition failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

// Obtain the selection variable

M_wdSel = m_wdApp.GetSelection ();

If (! M_wdSel.m_lpDispatch)

{

AfxMessageBox ("An error occurred while obtaining Select !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

// Get the Range variable of all DOC

M_wdRange = m_wdDoc.Range (vOptional, vOptional );

If (! M_wdRange.m_lpDispatch)

{

AfxMessageBox ("Range acquisition failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

Return TRUE;

}

BOOL CWordOffice: Open (CString fileName)

{

If (FALSE = CreateDocuments ())

{

Return FALSE;

}

Return OpenDocument (fileName );

}

BOOL CWordOffice: 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 Acquisition failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

// Obtain the selection variable

M_wdSel = m_wdApp.GetSelection ();

If (! M_wdsel.m_lpdispatch)

{

Afxmessagebox ("An error occurred while obtaining select !", Mb_ OK | mb_iconwarning );

Return false;

}

// Get the range variable of all Doc

M_wdrange = m_wddoc.range (voptional, voptional );

If (! M_wdrange.m_lpdispatch)

{

Afxmessagebox ("range acquisition failed !", Mb_ OK | mb_iconwarning );

Return false;

}

Hideapp ();

Return true;

}

Bool cwordoffice: savedocument ()

{

If (! M_wddoc.m_lpdispatch)

{

Afxmessagebox ("Document Acquisition failed !", Mb_ OK | mb_iconwarning );

Return false;

}

M_wddoc.save ();

Return true;

}

BOOL CWordOffice: SaveDocumentAs (CString fileName)

{

If (! M_wdDoc.m_lpDispatch)

{

AfxMessageBox ("Document Acquisition failed !", 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

);

Return TRUE;

}

BOOL CWordOffice: CloseDocument ()

{

COleVariant vTrue (short) TRUE ),

VFalse (short) FALSE ),

VOptional (long) DISP_E_PARAMNOTFOUND, VT_ERROR );

M_wdDoc.Close (vFalse, // SaveChanges.

VTrue, // OriginalFormat.

VFalse // RouteDocument.

);

M_wdDoc.AttachDispatch (m_wdApp.GetActiveDocument ());

If (! M_wdDoc.m_lpDispatch)

{

AfxMessageBox ("Document Acquisition failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

// Obtain the selection variable

M_wdSel = m_wdApp.GetSelection ();

If (! M_wdSel.m_lpDispatch)

{

AfxMessageBox ("An error occurred while obtaining Select !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

// Get the Range variable of all DOC

M_wdRange = m_wdDoc.Range (vOptional, vOptional );

If (! M_wdRange.m_lpDispatch)

{

AfxMessageBox ("Range acquisition failed !", MB_ OK | MB_ICONWARNING );

Return FALSE;

}

Return TRUE;

}

Void CWordOffice: 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.

);

// Release the memory to apply for resources

M_wdInlineShape.ReleaseDispatch ();

M_wdInlineShapes.ReleaseDispatch ();

// M_wdTb.ReleaseDispatch ();

M_wdrange.releasedispatch ();

M_wdsel.releasedispatch ();

// M_wdft.releasedispatch ();

M_wddoc.releasedispatch ();

M_wddocs.releasedispatch ();

M_wdapp.releasedispatch ();

}

Void cwordoffice: writetext (cstring sztext)

{

M_wdsel.typetext (sztext );

}

Void cwordoffice: 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 cwordoffice: writeendline (cstring sztext)

{

M_wdrange.insertafter (sztext );

}

Void cwordoffice: wholestory ()

{

M_wdrange.wholestory ();

}

Void cwordoffice: Copy ()

{

M_wdrange.copyaspicture ();

}

Void cwordoffice: 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 cwordoffice: insertshapes (cstring filename)

{

Colevariant vtrue (short) True ),

Vfalse (short) False ),

Voptional (long) disp_e_paramnotfound, vt_error );

M_wdinlineshapes = m_wdsel.getinlineshapes ();

M_wdinlineshape = m_wdinlineshapes.addpicture (filename, vfalse, vtrue, voptional );

}

Void cwordoffice: inserthyperlink (cstring filelink)

{

Colevariant vaddress (_ T (filelink), vsubaddress (_ T ("");

Range arange = m_wdsel.getrange ();

Hyperlinks vhyperlinks (arange. gethyperlinks ());

VHyperlinks. Add (

ARange, // Object, required. Converts a text or image to a hyperlink.

VAddress, // Variant type, optional. The address of the specified link. This address can be an email address, Internet address, or file name. Note that Microsoft Word does not check the correctness of the address.

VSubAddress, // Variant type, optional. Name of the location in the target file, such as bookmarks, named regions, or slide numbers.

VAddress, // Variant type, optional. The text displayed when the mouse pointer is placed on the specified hyperlink can be used as a "screen prompt. The default value is Address.

VAddress, // Variant type, optional. The text of the specified hyperlink. The value of this parameter replaces the text or image specified by Anchor.

VSubAddress // Variant type. Optional. The name of the frame or window in which the specified hyperlink is to be opened.

);

VHyperlinks. ReleaseDispatch ();

}

The above code is the main core code, and some code is not optimized. Please take a critical look!

The test code is as follows:

You need to add a button in the dialog box. The following code is added to the event Method of the button:

COfficeProjectDlg: OnButton1 ()

{

AfxEnableControlContainer ();

AfxOleInit ();

CWordOffice wd;

Wd. CreateDocuments ();

Wd. OpenDocument ("d: \ a.doc ");

Wd. ShowApp (); // display word

}

Other methods will not post the test method one by one. You can perform the test according to the method instructions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.