使用 Visual C++ MFC 和 Visual Studio 2015 自动化 Word 2016






4.95/5 (6投票s)
本文演示了使用 Visual Studio 2015 中的 Visual C++ MFC 自动化 Word 2016 的一些技术。
引言
几个月前,我有一个聊天应用程序项目。在该应用程序的对话区域,我使用 Rich Edit 控件来显示文本、表情符号、附件文件等。解决方案类似于这个项目:“一个显示位图和其他 OLE 对象的 Rich Edit 控件”,作者:Arthur:Mike O'Neill,非常感谢 Mike 先生的精彩文章。
归根结底,挑战在于如何将所有对话放入一个 word 文件中,让 Rich Edit 控件显示它们。在 CodeProject 网站上搜索了几分钟后,我找到了这篇文章 “使用 C++ MFC 应用程序在 Visual Studio 2008 中自动化 Excel 2007 并创建图表”,作者:abhinavsly,非常感谢 abhinavsly 先生的精彩文章。基于此,我尝试自动化 Word 并按照预期完成了我的项目。现在我想展示一个小型示例来自动化 Word 以供参考。
在本文中,我描述了如何打开 Word 应用程序,如何插入文本、超链接、插入图片,以及在您按下键盘上的任何键时执行相同的操作,等等。我使用 Visual Studio 2015 和 Office 2016 来进行此项目,但我相信它对于其他 Visual Studio 或 Microsoft Office 版本来说,工作方式也一样。
Using the Code
步骤 1:安装 Microsoft Office 2016 或其他版本
步骤 2:创建 AutomateWord 项目,如下所示
选择“基于对话框”的应用程序类型,单击“下一步”,“完成”以完成创建新项目。
步骤 3:在 Class Wizard 窗口中从 Typelib 添加类
从文件添加类,浏览到 “MSWORD.OLB”。
然后选择以下接口
_Application
注释
_Document
Documents
_Font
超链接
InlineShapes
Range
选择
步骤 4:将控件添加到对话框,如下所示
步骤 5:编码
打开 “AutomateWordDlg.h” 文件以添加接口的头文件
#include "CApplication.h"
#include "CComments.h"
#include "CDocuments.h"
#include "CDocument0.h"
#include "CFont0.h"
#include "CnlineShapes.h"
#include "CRange.h"
#include "CSelection.h"
#include "CHyperlinks.h"
此时,您需要在接口的头文件中注释掉以下所有行
#import "C:\\Program Files\\Microsoft Office\\Office16\\MSWORD.OLB" no_namespace
除非您将在 “msword.tlh” 文件中收到大量错误。现在,您可以尝试编译您的代码,它应该在没有任何错误的情况下完成。
将以下接口变量添加到 CAutomateWordDlg
类
CApplication m_iAppInterface;
CDocuments m_iDocuments;
CDocument0 m_iActiveDocument;
在使用 WORD 文件之前,您需要创建 Word 应用程序接口
BOOL CAutomateWordDlg::CreateApplicationInterface(BOOL bIsVisible)
{
if (!m_iAppInterface.CreateDispatch(_T("Word.Application")))
{
AfxMessageBox(_T("Cannot open the Word"));
return FALSE;
}
// Set visibility, show / hide
m_iAppInterface.put_Visible(bIsVisible);
return TRUE;
}
在 CreateApplicationInterface(BOOL bIsVisible)
函数中,如果将 bIsVisible
变量设置为 TRUE
,则 WORD 应用程序将与此应用程序一起显示,反之亦然。
接下来,通过添加按钮和控件的业务代码来完成应用程序,如下所示
打开一个现有的 WORD 文件并修改它
void CAutomateWordDlg::OnBnClickedAutomatewordOpen()
{
CFileDialog fdlgFileChooser(true, _T("*.*"), 0,
4 | 2, _T("Microsoft Word Files|*.*"));
if (fdlgFileChooser.DoModal() == IDCANCEL)
{
return;
}
if (IsFileExisted(fdlgFileChooser.GetPathName()))
{
// Create application interface with visibility option
if (!CreateApplicationInterface(
((CButton *)GetDlgItem
(IDC_AUTOMATEWORD_VISIBLE))->GetCheck() == BST_CHECKED))
{
return;
}
COleVariant ovTrue((short)TRUE);
COleVariant ovFalse((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
// Get Documents
m_iDocuments = m_iAppInterface.get_Documents();
// Open a Document
m_iActiveDocument =
m_iDocuments.Open(COleVariant(fdlgFileChooser.GetPathName()),
ovOptional, ovOptional, ovOptional,
ovOptional, ovOptional, ovOptional,
ovOptional, ovOptional, ovOptional,
ovOptional, ovOptional, ovOptional,
ovOptional, ovOptional, ovOptional);
CSelection iSelection = m_iAppInterface.get_Selection();
// Go to the end of the document before editing
iSelection.GoTo(COleVariant((short)3),
COleVariant((short)-1),
ovOptional,
ovOptional); // 3 = wdGoToLine; -1 = wdGoToLast
EnableControls(TRUE);
}
}
成功打开 WORD 文件后,您应该使用 CSelection:: GoTo()
将光标移动到文档末尾以进行编辑,如上所示。
创建一个新的 WORD 文件
void CAutomateWordDlg::OnBnClickedAutomatewordNew()
{
// Create application interface with visibility option
if (!CreateApplicationInterface(
((CButton *)GetDlgItem(IDC_AUTOMATEWORD_VISIBLE))->GetCheck() == BST_CHECKED))
{
return;
}
COleVariant ovTrue((short)TRUE);
COleVariant ovFalse((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
// Get Documents
m_iDocuments = m_iAppInterface.get_Documents();
// Create a new Document
m_iActiveDocument = m_iDocuments.Add(ovOptional, ovOptional, ovOptional, ovOptional);
EnableControls(TRUE);
}
保存并关闭文档
void CAutomateWordDlg::OnBnClickedAutomatewordClose()
{
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
// Save before closing (Prompt the "Save as" dialog if this is a new document)
m_iActiveDocument.Save();
// Close the active document
m_iActiveDocument.Close(ovOptional, ovOptional, ovOptional);
// Release dispatch for valid re-creating dispatch in Open / New document activities
m_iAppInterface.ReleaseDispatch();
EnableControls(FALSE);
}
保存并关闭所有文档
void CAutomateWordDlg::OnBnClickedAutomatewordCloseall()
{
COleVariant ovNoPrompt((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
// Save all documents (Prompt the "Save as" dialog if this is a new document)
m_iDocuments.Save(ovNoPrompt, ovOptional);
// Close all documents
m_iDocuments.Close(ovOptional, ovOptional, ovOptional);
// Release dispatch for valid re-creating dispatch in Open / New document activities
m_iAppInterface.ReleaseDispatch();
EnableControls(FALSE);
}
向文档添加文本
void CAutomateWordDlg::OnBnClickedAutomatewordAddText()
{
COleVariant ovTrue((short)TRUE);
COleVariant ovFalse((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
CString strText;
// Get text
GetDlgItemText(IDC_AUTOMATEWORD_TEXT, strText);
CSelection iSelection = m_iAppInterface.get_Selection();
// Add text into the document
iSelection.TypeText(strText);
// Add a paragraph (return & new line)
iSelection.TypeParagraph();
}
向文档添加超链接
void CAutomateWordDlg::OnBnClickedAutomatewordAddHyperlinks()
{
COleVariant ovTrue((short)TRUE);
COleVariant ovFalse((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
CString strText;
// Get text
GetDlgItemText(IDC_AUTOMATEWORD_TEXT, strText);
CSelection iSelection = m_iAppInterface.get_Selection();
// Add a hyperlink to the home page.
CHyperlinks iHyperlinks = iSelection.get_Hyperlinks();
iHyperlinks.Add(iSelection.get_Range(),
COleVariant(strText),
ovOptional,
ovOptional,
ovOptional,
ovOptional);
// Add a paragraph (return & new line)
iSelection.TypeParagraph();
}
向文档插入图片
void CAutomateWordDlg::OnBnClickedAutomatewordInsertPicture()
{
COleVariant ovTrue((short)TRUE);
COleVariant ovFalse((short)FALSE);
COleVariant ovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
CFileDialog fdlgPicture(TRUE);
if (fdlgPicture.DoModal() == IDCANCEL)
{
return;
}
CSelection iSelection = m_iAppInterface.get_Selection();
CnlineShapes iInlineShapes = iSelection.get_InlineShapes();
COleVariant ovLinkToFile((short)0);
COleVariant ovSaveWithDocument((short)1);
// Insert picture
iInlineShapes.AddPicture(fdlgPicture.GetPathName(),
ovLinkToFile,
ovSaveWithDocument,
ovOptional);
// Add a paragraph (return & new line)
iSelection.TypeParagraph();
}
设置文本的字体
void CAutomateWordDlg::OnBnClickedAutomatewordSetSelectionTextFont()
{
CFontDialog fdlgFont;
if (fdlgFont.DoModal() == IDCANCEL)
{
return;
}
CSelection iSelection = m_iAppInterface.get_Selection();
CFont0 iFont = iSelection.get_Font();
iFont.put_Name(fdlgFont.GetFaceName());
iFont.put_Size((float)fdlgFont.GetSize() / 10);
iFont.put_Color(fdlgFont.GetColor());
iFont.put_Bold(fdlgFont.IsBold());
iFont.put_Italic(fdlgFont.IsItalic());
}
当您按下键盘上的 BACKSPACE、DELETE、LEFT、RIGHT、UP、DOWN 键时,执行相同的操作
void CAutomateWordDlg::OnBnClickedAutomatewordBackspace()
{
CSelection iSelection = m_iAppInterface.get_Selection();
iSelection.TypeBackspace();
}
void CAutomateWordDlg::OnBnClickedAutomatewordDelete()
{
CSelection iSelection = m_iAppInterface.get_Selection();
COleVariant ovUnit((short)1);
COleVariant ovCount((short)1);
iSelection.Delete(ovUnit, ovCount);
}
void CAutomateWordDlg::OnBnClickedAutomatewordLeft()
{
CSelection iSelection = m_iAppInterface.get_Selection();
COleVariant ovUnit((short)1);
COleVariant ovCount((short)1);
COleVariant ovExtend((short)(((CButton *)GetDlgItem
(IDC_AUTOMATEWORD_SELECTION))->GetCheck() == BST_CHECKED));
iSelection.MoveLeft(ovUnit, ovCount, ovExtend);
}
void CAutomateWordDlg::OnBnClickedAutomatewordRight()
{
CSelection iSelection = m_iAppInterface.get_Selection();
COleVariant ovUnit((short)1);
COleVariant ovCount((short)1);
COleVariant ovExtend((short)(((CButton *)GetDlgItem
(IDC_AUTOMATEWORD_SELECTION))->GetCheck() == BST_CHECKED));
iSelection.MoveRight(ovUnit, ovCount, ovExtend);
}
void CAutomateWordDlg::OnBnClickedAutomatewordUp()
{
CSelection iSelection = m_iAppInterface.get_Selection();
COleVariant ovUnit((short)5);
COleVariant ovCount((short)1);
COleVariant ovExtend((short)(((CButton *)GetDlgItem
(IDC_AUTOMATEWORD_SELECTION))->GetCheck() == BST_CHECKED));
iSelection.MoveUp(ovUnit, ovCount, ovExtend);
}
void CAutomateWordDlg::OnBnClickedAutomatewordDown()
{
CSelection iSelection = m_iAppInterface.get_Selection();
COleVariant ovUnit((short)5);
COleVariant ovCount((short)1);
COleVariant ovExtend((short)(((CButton *)GetDlgItem
(IDC_AUTOMATEWORD_SELECTION))->GetCheck() == BST_CHECKED));
iSelection.MoveDown(ovUnit, ovCount, ovExtend);
}
构建并运行您的项目,尽情享受吧。我们可以做很多事情来自动化 Word,但我保持这个项目非常简单,以便于理解。我将在下一篇文章中尝试做更多有趣的事情。
关注点
有关使用 Visual Studio 进行 Microsoft Office 开发的更多详细信息,您可以访问以下官方链接
历史
- 2016 年 10 月 22 日:版本 1.0