折腾了将近一个月的WORD文档开发终于告一段落。这件事已经很多大牛已经做过了。并且很多方法都已经非常详细,提供的资料也非常齐全。不过由于时间的久远并且较为散乱。所以我在学习时间过程中还是走了一些些弯路。所以想整理一下自己的成果,供自己后期复习以及分享。
我的平台是 WIN7+VS2005+WORD2003;
一、通过VC++6.0提取需要文档
整个程序需要调用word进程进行操作,所以我们必须要包含word的接口文件。
根据wowolook的博客http://blog.csdn.net/wowolook/article/details/8509664
我们必须要添加类型库word2003相对应的类型库是MSWord.olb 。
如果你使用VS2005添加类->TypeLib中的MFC类,然后找到OFFICE安装路径下的MSword.olb,你会发现你选择一个函数就会生成一个头文件,到最后你全选过后发现‘头文件’里多了n++的头文件,即使你全部包含到工程中,依旧会报错。但如果使用VC++6.0来添加,则只会生成msword.h和msword.cpp两个文件。不单单方便、简单、并且好使用。使用的时候只需要
#include “msword.h” 就可以了。因为我的工程只能在VS2005下进行,所以我必须得弄到这两个文件。所以我只能在再安装一个VC++6.0。然后通过VC++6.0来生成msword.h和msword.cpp两个文件,然后再拷贝到VS2005的工程中。有些大牛已经给出了这两个文件,不过他们生成的时候并没有包含全部的函数。所以我只能自己生成。我一会把这两个文件上传到论坛里,直接下载拷贝到工程中就可以使用 :) 。
--------------------------------------------------------------------------------
msword.h和msword.cpp文档下载:
http://download.csdn.net/detail/skyhuangdan/6995993
---------------------------------------------------------------------------------
二、具体步骤
CoInitialize(NULL),调用完毕后 CoUninitialize()。
三、封装msword相关操作
#pragma once #include "msword.h" class CMyWord
{
public:
CMyWord(void);
public:
~CMyWord(void); private: //待操作变量
_Application m_wdApp; //wordApp
Documents m_wdDocs; //wordDocs
_Document m_wdDoc; //wordDoc
Selection m_wdSel; //wordSelection
Range m_wdRange; //wordRange
InlineShapes m_wdInlineShapes;
InlineShape m_wdInlineShape; Tables m_wdTables; // Tables wordTables;
Table m_wdTable; // Table wordTable;
Cell m_wdCell; // Cell wordCell;
Cells m_wdCells; // Cells wordCells;
_Font m_wdFont; // _Font wordFont;
Shading m_wdShading; // Shading wordShading;
Paragraphs m_wdParagraphs; // Paragraphs wordParagraphs; public:
/*-------------------------文档操作------------------------------------*/
BOOL Create(); //创建进程,打开窗口,打开版面
void HideApp();
void ShowApp();
BOOL SaveDocumentAs(CString FileName);
void CloseApp(); //关闭程序
void PrintWord(); //连接实体打印机打印
BOOL SaveDocAsPDF(CString FileName); //保存为PDF文件 /*--------------------------文字操作-------------------------------------*/
void WriteText(CString szText); //当前光标处写文本
void WriteNewLineText(CString szText, int nLineCount = 1); //换N行写字
void WriteEndLine(CString szText); //文档结尾处写文本
void ChangeFontSize(float num); //更改字体大小
void ChangeFontToggle(); //是否加粗字体
void NewLine(int nLineCount = 1); //实现向下切换n行 /*---------------------------图片插入------------------------------------*/
void InsertShapes(CString fileName); //在当前光标的位置插入图片 /*---------------------------表格操作------------------------------------*/
void InsertTable(int row, int column); //在当前光标的位置插入表格
void MoveRight(int nRight = 1); //光标向右移动n次,默认一次
void MoveLeft(int nLeft = 1); //光标向左
void MoveDown(int nDown = 1); //光标向下
void MoveUp(int nUp = 1); //光标向上 };
#include "StdAfx.h"
#include "MyWord.h" CMyWord::CMyWord()
{
Create();
} CMyWord::~CMyWord()
{
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.
);
//释放申请资源
m_wdParagraphs.ReleaseDispatch();
m_wdShading.ReleaseDispatch();
m_wdFont.ReleaseDispatch();
m_wdCells.ReleaseDispatch();
m_wdCell.ReleaseDispatch();
m_wdTable.ReleaseDispatch();
m_wdTables.ReleaseDispatch();
m_wdInlineShape.ReleaseDispatch();
m_wdInlineShapes.ReleaseDispatch();
m_wdRange.ReleaseDispatch();
m_wdSel.ReleaseDispatch();
m_wdDoc.ReleaseDispatch();
m_wdDocs.ReleaseDispatch();
m_wdApp.ReleaseDispatch(); } BOOL CMyWord::Create()
{
//CreateDocuments
//CreateApp
if (FALSE == m_wdApp.CreateDispatch(_T("Word.Application")))
{
AfxMessageBox(_T("Application创建失败,请确保安装了word 2000或以上版本!"), MB_OK|MB_ICONWARNING);
return FALSE;
} m_wdDocs.AttachDispatch(m_wdApp.GetDocuments());
if (!m_wdDocs.m_lpDispatch)
{
AfxMessageBox(_T("Documents创建失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
} //CreateDocument
if (!m_wdDocs.m_lpDispatch)
{
AfxMessageBox(_T("Documents为空!"), MB_OK|MB_ICONWARNING);
return FALSE;
} COleVariant varTrue(short(1),VT_BOOL),vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
CComVariant Template(_T("C:\\TSINGHUA.doc")); //使用TSINGHUA的文档模板
CComVariant NewTemplate(false),DocumentType(0),Visible; m_wdDocs.Add(&Template,&NewTemplate,&DocumentType,&Visible); //得到document变量
m_wdDoc = m_wdApp.GetActiveDocument();
if (!m_wdDoc.m_lpDispatch)
{
AfxMessageBox(_T("Document获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
//得到selection变量
m_wdSel = m_wdApp.GetSelection();
if (!m_wdSel.m_lpDispatch)
{
AfxMessageBox(_T("Select获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
//得到Range变量
m_wdRange = m_wdDoc.Range(vOptional,vOptional);
if(!m_wdRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
} return TRUE; } void CMyWord::ShowApp()
{
m_wdApp.SetVisible(TRUE);
} void CMyWord::HideApp()
{
m_wdApp.SetVisible(FALSE);
} BOOL CMyWord::SaveDocumentAs(CString fileName)
{
if (!m_wdDoc.m_lpDispatch)
{
AfxMessageBox(_T("Document获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
COleVariant vFileName(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,
vOptional,
vOptional,
vOptional,
vOptional,
vOptional
);
return TRUE;
} void CMyWord::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.
);
//释放申请资源
m_wdParagraphs.ReleaseDispatch();
m_wdShading.ReleaseDispatch();
m_wdFont.ReleaseDispatch();
m_wdCells.ReleaseDispatch();
m_wdCell.ReleaseDispatch();
m_wdTable.ReleaseDispatch();
m_wdTables.ReleaseDispatch();
m_wdInlineShape.ReleaseDispatch();
m_wdInlineShapes.ReleaseDispatch();
m_wdRange.ReleaseDispatch();
m_wdSel.ReleaseDispatch();
m_wdDoc.ReleaseDispatch();
m_wdDocs.ReleaseDispatch();
m_wdApp.ReleaseDispatch();
} void CMyWord::PrintWord()
{
//m_wdApp.SetActivePrinter(_T("\\166.111.52.59\\HP LaserJet 1020")); //应该先设置所选择的打印机,这里是打印机的名字,如果不设置则会选择之前的默认设置
m_wdDoc = m_wdApp.GetActiveDocument();
if(!m_wdDoc.m_lpDispatch)
{
AfxMessageBox(_T("获取激活文档对象失败"));
return;
}
else
{
COleVariant covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_wdDoc.PrintOut(covFalse, // Background.
covOptional, // Append.
covOptional, // Range.
covOptional, // OutputFileName.
covOptional, // From.
covOptional, // To.
covOptional, // Item.
COleVariant((long)1), // Copies.
covOptional, // Pages.
covOptional, // PageType.
covOptional, // PrintToFile.
covOptional, // Collate.
covOptional, // ActivePrinterMacGX.
covOptional, // ManualDuplexPrint.
covOptional, // PrintZoomColumn New with Word 2002
covOptional, // PrintZoomRow ditto
covOptional, // PrintZoomPaperWidth ditto
covOptional); // PrintZoomPaperHeight ditto*/
} } BOOL CMyWord::SaveDocAsPDF(CString FileName)
{ m_wdApp.SetActivePrinter(_T("Foxit Reader PDF Printer")); //设置为打印机的名字!!!!! m_wdDoc = m_wdApp.GetActiveDocument();
if(!m_wdDoc.m_lpDispatch)
{
AfxMessageBox(_T("获取激活文档对象失败"));
return false;
}
else
{
COleVariant covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_wdDoc.PrintOut(covFalse, // Background.
covOptional, // Append.
covOptional, // Range.
COleVariant(FileName), // OutputFileName.
covOptional, // From.
covOptional, // To.
covOptional, // Item.
COleVariant((long)1), // Copies.
covOptional, // Pages.
covOptional, // PageType.
covOptional, // PrintToFile.
covOptional, // Collate.
covOptional, // ActivePrinterMacGX.
covOptional, // ManualDuplexPrint.
covOptional, // PrintZoomColumn New with Word 2002
covOptional, // PrintZoomRow ditto
covOptional, // PrintZoomPaperWidth ditto
covOptional); // PrintZoomPaperHeight ditto*/
} return TRUE; } void CMyWord::WriteText(CString szText)
{
m_wdSel.TypeText(szText);
} void CMyWord::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 CMyWord::WriteEndLine(CString szText)
{
m_wdRange.InsertAfter(szText);
} //改变字体
void CMyWord::ChangeFontSize(float num)
{
m_wdFont = m_wdSel.GetFont();
m_wdFont.SetSize(num); } //字体加粗
void CMyWord::ChangeFontToggle()
{
const int Toggle = 9999998;
m_wdFont = m_wdSel.GetFont();
m_wdFont.SetBold(Toggle);
} //实现换行,n
void CMyWord::NewLine(int nLineCount)
{
int i;
if (nLineCount <= 0)
{
nLineCount = 0;
}
for (i = 0; i < nLineCount; i++)
{
m_wdSel.TypeParagraph();
} } void CMyWord::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 CMyWord::InsertTable(int row, int column)
{
m_wdTables = m_wdSel.GetTables();
m_wdRange = m_wdSel.GetRange();
const int wdWordTableBehavior = 1;
const int wdAutoFitFixed = 0; m_wdTables.Add( m_wdRange,
row,
column,
COleVariant((short)wdWordTableBehavior),
COleVariant((short)wdAutoFitFixed));
} void CMyWord::MoveRight(int nRight)
{
m_wdSel.MoveRight(COleVariant((short)1),
COleVariant((short)nRight),
COleVariant((short)0)); } void CMyWord::MoveLeft(int nLeft)
{
m_wdSel.MoveLeft(COleVariant((short)1),
COleVariant((short)nLeft),
COleVariant((short)0)); } //向上移动鼠标到上一行
void CMyWord::MoveDown(int nDown)
{
m_wdSel.MoveDown(COleVariant((short)5),
COleVariant((short)nDown),
COleVariant((short)0)); } //向上移动鼠标到上一行
void CMyWord::MoveUp(int nUp)
{
m_wdSel.MoveUp(COleVariant((short)5),
COleVariant((short)nUp),
COleVariant((short)0)); } /*---------------------------------------------------------------------------*/
#include "MyWord.h" void Cword15Dlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码 CMyWord App;
App.ShowApp();
//AfxMessageBox(_T("看到弹出的窗口了吗?")); for(int i = 0;i < 3;i++)
App.WriteText(_T("这是测试字体。。。测试字体。字体大小默认。未加粗!\n")); App.ChangeFontSize(20);
App.WriteText(_T("这是测试字体。。。测试字体。字体大小20。未加粗!\n")); App.ChangeFontToggle();
App.WriteText(_T("这是测试字体。。。测试字体。字体大小20。加粗!\n")); App.InsertShapes(_T("C:\\TSINGHUA.jpg"));
App.InsertTable(2,5); AfxMessageBox(_T("看到你需呀的了吗?我要保存了哦!"));
//App.SaveDocumentAs(_T("C:\\helloTHU.doc"));
//App.PrintWord();
App.SaveDocAsPDF(_T("C:\\helloTHU.pdf")); OnOK();
}
在此特别说明的函数是 打印函数。 由于工程需要不仅仅需要doc文档还需要PDF文档。所以我希望能够直接生成两个文档。(这样就可以避免去操作PDFLib库 哈哈~)