C++操作word:插入文字、图片、表格,设置样式字体

时间:2021-07-31 06:22:45

想要控制word文档,向word写入文字,图片,表格等并控制其格式,可以引入第三方库,#include "msword.h",网上的资料很多,在此不再赘述。下面封装好的代码,C++操作word:插入文字、图片、表格,设置样式字体,很简单,可以直接调用:


// WordHandle.h: interface for the WordHandle class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_WORDHANDLE_H__7F5096E5_F09B_4DA1_9FC2_28FA2D2C1573__INCLUDED_)
#define AFX_WORDHANDLE_H__7F5096E5_F09B_4DA1_9FC2_28FA2D2C1573__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000


//段落对齐方式
enum wdAlignParagraphAlignment {
wdAlignParagraphLeft = 0, //左对齐
wdAlignParagraphCenter = 1, //居中
wdAlignParagraphRight = 2, //右对齐
wdAlignParagraphJustify = 3 //两端对齐
};

//单元格垂直对齐方式
enum WdCellVerticalAlignment{
wdCellAlignVerticalTop = 0, //文字与单元格上框线对齐
wdCellAlignVerticalCenter = 1, //文字与单元格中心对齐
wdCellAlignVerticalBottom = 3 //文字与单元格底边框线对齐
};

#include "msword.h"
#include <atlbase.h>
#include "comdef.h"
#include <afxdisp.h> //COlVirant


class WordHandle
{
private:
_Application wordapp;
COleVariant vTrue, vFalse, vOptional;
Documents worddocs;
CComVariant tpl, Visble, DocType, NewTemplate;
Selection wordsel;
_Document worddoc;
Tables wordtables;
Table wordtable;
_ParagraphFormat paragraphformat;
Cell cell;
Cells cells;
_Font wordFt;
Range range;
CComVariant SaveChanges,OriginalFormat,RouteDocument;
CComVariant ComVariantTrue,ComVariantFalse;
InlineShapes ishaps;
InlineShape ishap;


public:
void AddPicture(LPCTSTR picname);
void AddTime(CTime time);
void CreateChart();
BOOL MergeCell(int cell1row,int cell1col,int cell2row,int cell2col);
void CloseWordSave(LPCTSTR wordname);
void CloseWord();
void SetTableFormat(int nRow, int nColumn, long horizontalAlignment, long verticalAlignment);
void SetTableFormat(int beginRow, int beginColumn, int endRow, int endColumn, long horizontalAlignment = wdAlignParagraphCenter, long verticalAlignment =

wdCellAlignVerticalCenter);
void SetTablePadding(float topPadding = 4.0, float bottomPadding = 4.0, float leftPadding = 4.0, float rightPadding = 4.0);
void SetTableFont(int nRow, int nColumn, BOOL bBold, BOOL bItalic = FALSE, BOOL bUnderLine = FALSE);
void SetTableFont(int nRow, int nColumn, LPCTSTR szFontName = "宋体", float fSize=9, long lFontColor=0, long lBackColor = 0);
void SetTableFont(int beginRow, int beginColumn, int endRow, int endColumn, LPCTSTR szFontName = "宋体", float fSize=9, long lFontColor=0, long lBackColor =

0);
void SetFont(BOOL bBold, BOOL bItalic = FALSE, BOOL bUnderLine = FALSE );
void SetFont(LPCTSTR szFontName ,float fSize = 9, long lFontColor = 0, long lBackColor=0);
void AddParagraph();
void WriteText(LPCTSTR szText);
BOOL CreateWord();
void ShowWord(BOOL show);
void WriteCell(int nRow, int nColumne, LPCTSTR szText);
void WriteCell(int nRow, int nColumne, LPCTSTR lpszFormat, float num);
BOOL CreateTable(int nRow, int nColumn);
void SetParagraphFormat(int nAlignment);
BOOL CreateDocumtent();
BOOL CreateApp();
WordHandle();
virtual ~WordHandle();

};

#endif // !defined(AFX_WORDHANDLE_H__7F5096E5_F09B_4DA1_9FC2_28FA2D2C1573__INCLUDED_)


下面是实现文件:


// WordHandle.cpp: implementation of the WordHandle class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "WordHandle.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

WordHandle::WordHandle(){
OleInitialize(NULL);
//CoInitialize(NULL);
ComVariantTrue=CComVariant(true);
ComVariantFalse=CComVariant(false);
vTrue=COleVariant((short)TRUE);
vFalse=COleVariant ((short)FALSE);
tpl=CComVariant(_T(""));
DocType=CComVariant(0);
NewTemplate=CComVariant(false);
vOptional=COleVariant((long)DISP_E_PARAMNOTFOUND,VT_ERROR);

}

WordHandle::~WordHandle(){
wordtable.ReleaseDispatch();
wordtables.ReleaseDispatch();
wordsel.ReleaseDispatch();
worddocs.ReleaseDispatch();
worddoc.ReleaseDispatch();
paragraphformat.ReleaseDispatch();
wordapp.ReleaseDispatch();
wordFt.ReleaseDispatch();
cell.ReleaseDispatch();
range.ReleaseDispatch();
ishaps.ReleaseDispatch();
ishap.ReleaseDispatch();
CoUninitialize();
}

BOOL WordHandle::CreateApp(){
if (FALSE == wordapp.CreateDispatch("Word.Application")){
MessageBox(NULL,"Application创建失败!","", MB_OK|MB_ICONWARNING);
return FALSE;
}
// m_wdApp.SetVisible(TRUE);
return TRUE;

}

BOOL WordHandle::CreateDocumtent(){
if (!wordapp.m_lpDispatch){
MessageBox(NULL,"Application为空,Documents创建失败!", "错误提示",MB_OK|MB_ICONWARNING);
return FALSE;
}
worddocs.AttachDispatch(wordapp.GetDocuments());
if (!worddocs.m_lpDispatch){
MessageBox(NULL,"Documents创建失败!", "错误提示",MB_OK|MB_ICONWARNING);
return FALSE;
}
CComVariant Template(_T(""));
CComVariant NewTemplate(false),DocumentType(0),Visible;
worddocs.Add(&Template,&NewTemplate,&DocumentType,&Visible);

worddocs = wordapp.GetActiveDocument();
if (!worddocs.m_lpDispatch){
MessageBox(NULL,"Document获取失败!", "",MB_OK|MB_ICONWARNING);
return FALSE;
}
wordsel = wordapp.GetSelection();
if (!wordsel.m_lpDispatch){
MessageBox(NULL,"Select获取失败!", "",MB_OK|MB_ICONWARNING);
return FALSE;
}
return TRUE;

}

void WordHandle::SetParagraphFormat(int nAlignment)
{
if (!wordsel.m_lpDispatch){
return ;
}
paragraphformat = wordsel.GetParagraphFormat();
paragraphformat.SetAlignment(nAlignment);
wordsel.SetParagraphFormat(paragraphformat);
}

BOOL WordHandle::CreateTable(int nRow, int nColumn){
if (!wordapp.m_lpDispatch){
return FALSE;
}

worddoc = wordapp.GetActiveDocument();
wordtables = worddoc.GetTables();
VARIANT vtDefault, vtAuto;
vtDefault.vt = VT_I4;
vtAuto.vt = VT_I4;
vtDefault.intVal = 1;
vtAuto.intVal = 0;
wordtables.Add(wordsel.GetRange(), nRow, nColumn, &vtDefault, &vtAuto);
wordtable = wordtables.Item(wordtables.GetCount());

VARIANT vtstyle;
vtstyle.vt = VT_BSTR;
_bstr_t bstr = "网格型";
vtstyle.bstrVal = bstr;
if (wordtable.GetStyle().bstrVal == vtstyle.bstrVal){
wordtable.SetStyle(&vtstyle);
wordtable.SetApplyStyleFirstColumn(TRUE);
wordtable.SetApplyStyleHeadingRows(TRUE);
wordtable.SetApplyStyleLastColumn(TRUE);
wordtable.SetApplyStyleLastRow(TRUE);
}
return TRUE;
}

void WordHandle::WriteCell(int nRow, int nColumne, LPCTSTR szText){
if (wordtable!=NULL){
cell = wordtable.Cell(nRow,nColumne);
cell.Select();
wordsel.TypeText(szText);
}
}

//将数字num以lpszFormat的形式写入(nRow,nColumne)中
void WordHandle::WriteCell(int nRow, int nColumne, LPCTSTR lpszFormat, float num){
if(wordtable != NULL){
cell = wordtable.Cell(nRow, nColumne);
cell.Select();
CString str;
str.Format(lpszFormat, num);
wordsel.TypeText(str);
}
}

void WordHandle::ShowWord(BOOL show){
if (!wordapp.m_lpDispatch){
return ;
}
wordapp.SetVisible(show);
}

BOOL WordHandle::CreateWord(){
if (FALSE == CreateApp()){
return FALSE;
}
return CreateDocumtent();
}

//输出文字
void WordHandle::WriteText(LPCTSTR szText){
if (!wordsel.m_lpDispatch){
return ;
}
wordsel.TypeText(szText);
wordtable=NULL;
}

//添加新段落
void WordHandle::AddParagraph(){
if (!wordsel.m_lpDispatch){
return ;
}
wordsel.EndKey(COleVariant((short)6),COleVariant(short(0))); //定位到全文末尾
wordsel.TypeParagraph();//新的段落,也就是回车换行
wordtable=NULL;
}

//设置字体样式、字体大小、字体颜色、背景色
void WordHandle::SetFont(LPCTSTR szFontName, float fSize, long lFontColor, long lBackColor){
if (!wordsel.m_lpDispatch){
MessageBox(NULL,"Select为空,字体设置失败!","错误提示", MB_OK|MB_ICONWARNING);
return;
}
wordsel.SetText("F");
wordFt = wordsel.GetFont();
wordFt.SetSize(fSize);
wordFt.SetName(szFontName);
wordFt.SetColor(lFontColor);
wordsel.SetFont(wordFt);
range = wordsel.GetRange();
range.SetHighlightColorIndex(lBackColor);
}

//设置粗体、斜体、下划线
void WordHandle::SetFont(BOOL bBold, BOOL bItalic, BOOL bUnderLine){
if (!wordsel.m_lpDispatch){
MessageBox(NULL,"Select为空,字体设置失败!", "错误提示",MB_OK|MB_ICONWARNING);
return;
}
wordsel.SetText("F");
wordFt = wordsel.GetFont();
wordFt.SetBold(bBold);
wordFt.SetItalic(bItalic);
wordFt.SetUnderline(bUnderLine);
wordsel.SetFont(wordFt);
}

//设置单元格(nRow, nColumn)字体样式、字体大小、字体颜色、背景色
void WordHandle::SetTableFont(int nRow, int nColumn, LPCTSTR szFontName, float fSize, long lFontColor, long lBackColor){
cell = wordtable.Cell(nRow, nColumn);
cell.Select();
wordFt = wordsel.GetFont();
wordFt.SetName(szFontName);
wordFt.SetSize(fSize);
wordFt.SetColor(lFontColor);
wordsel.SetFont(wordFt);
range = wordsel.GetRange();
range.SetHighlightColorIndex(lBackColor);
}

//设置从(beginRow, beginColumn)到(endRow, endColumn)所围区域单元格的字体样式、字体大小、字体颜色、背景色
void WordHandle::SetTableFont(int beginRow, int beginColumn, int endRow, int endColumn, LPCTSTR szFontName, float fSize, long lFontColor, long lBackColor){
wordtable.SetBottomPadding(10.0);
int nRow, nColumn;
for(nRow = beginRow; nRow <= endRow; nRow++){
for(nColumn = beginColumn; nColumn <= endColumn; nColumn++){
SetTableFont(nRow, nColumn, szFontName, fSize, lFontColor, lBackColor);
}
}
}

//设置单元格(nRow, nColumn)粗体、斜体、下划线
void WordHandle::SetTableFont(int nRow, int nColumn, BOOL bBold, BOOL bItalic, BOOL bUnderLine){
cell = wordtable.Cell(nRow, nColumn);
cell.Select();
wordFt = wordsel.GetFont();
wordFt.SetBold(bBold);
wordFt.SetItalic(bItalic);
wordFt.SetUnderline(bUnderLine);
wordsel.SetFont(wordFt);
}

//设置表格单元格(nRow, nColumn)的水平、垂直对齐方式
void WordHandle::SetTableFormat(int nRow, int nColumn, long horizontalAlignment, long verticalAlignment){
cell = wordtable.Cell(nRow, nColumn);
cell.Select();
cell.SetVerticalAlignment(verticalAlignment);
paragraphformat = wordsel.GetParagraphFormat();
paragraphformat.SetAlignment(horizontalAlignment);
wordsel.SetParagraphFormat(paragraphformat);
}

//设置表格从(beginRow, beginColumn)到(endRow, endRow)区域内水平、垂直对齐方式
void WordHandle::SetTableFormat(int beginRow, int beginColumn, int endRow, int endColumn, long horizontalAlignment, long verticalAlignment){
int nRow, nColumn;
for( nRow = beginRow; nRow <= endRow; nRow++){
for( nColumn = beginColumn; nColumn <= endColumn; nColumn++){
SetTableFormat(nRow, nColumn, horizontalAlignment, verticalAlignment);
}
}
}

//设置表格单元格的上下左右内边距填充
void WordHandle::SetTablePadding(float topPadding, float bottomPadding, float leftPadding, float rightPadding){
wordtable.SetTopPadding(topPadding);
wordtable.SetBottomPadding(bottomPadding);
wordtable.SetLeftPadding(leftPadding);
wordtable.SetRightPadding(rightPadding);
}

//合并单元格
BOOL WordHandle::MergeCell(int cell1row, int cell1col, int cell2row, int cell2col){
Cell cell1=wordtable.Cell(cell1row,cell1col);
Cell cell2=wordtable.Cell(cell2row,cell2col);
cell1.Merge(cell2);

return TRUE;
}

//创建图表
void WordHandle::CreateChart(){
ishaps=wordsel.GetInlineShapes();
CComVariant classt;
classt=CComVariant("MSGraph.Chart.8");
ishap=ishaps.AddOLEObject(&classt,vOptional,vFalse,vFalse,vOptional,vOptional,vOptional,vOptional);
AddParagraph();
}

//添加图片
void WordHandle::AddPicture(LPCTSTR picname){

ishaps=wordsel.GetInlineShapes();
ishap=ishaps.AddPicture(picname,vFalse,vTrue,vOptional);

AddParagraph();
}

void WordHandle::AddTime(CTime time){
}

void WordHandle::CloseWord(){
if (!wordapp.m_lpDispatch){
return ;
}
SaveChanges=ComVariantFalse;
wordapp.Quit(&SaveChanges,&OriginalFormat,&RouteDocument);
}

void WordHandle::CloseWordSave(LPCTSTR wordname){
if (!wordapp.m_lpDispatch){
return ;
}
if (!worddoc.m_lpDispatch){
return ;
}
worddoc.SaveAs(&CComVariant(wordname),
&CComVariant((short)0),
vFalse, &CComVariant(""), vTrue, &CComVariant(""),
vFalse, vFalse, vFalse, vFalse, vFalse,
vFalse, vFalse, vFalse, vFalse, vFalse);
SaveChanges=ComVariantTrue;
wordapp.Quit(&SaveChanges,&OriginalFormat,&RouteDocument);
}

如下是调用函数,比较简单哦!


void CAutotestView::OnBtn1Click() 
{

WordHandle wordHandle;
wordHandle.CreateWord();

// 获取应用当前Debug路径
char fileName[MAX_PATH];
GetModuleFileName(NULL, fileName, MAX_PATH);
char dir[260];
char dirver[100];
_splitpath(fileName, dirver, dir, NULL, NULL);
CString strAppPath = dirver;
strAppPath += dir;
wordHandle.AddPicture(strAppPath+"\\logo.bmp"); //必须保证debug目录下有一张logo图片

wordHandle.AddParagraph();
wordHandle.SetParagraphFormat(wdAlignParagraphCenter);
wordHandle.SetFont(_T("黑体"), 18);
wordHandle.WriteText(_T("XXXXXXXXXX测试报告"));

wordHandle.AddParagraph();
wordHandle.AddParagraph();
wordHandle.SetFont(_T("宋体"), 10);
wordHandle.SetParagraphFormat(wdAlignParagraphRight);
wordHandle.WriteText(_T("生成时间:"));
wordHandle.WriteText(CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S")));

//连接access数据库TestInfoSet
CString strSQL;
CAutotestApp* ptheApp = (CAutotestApp *) AfxGetApp();
strSQL.Format("select * from TestInfo where TestID = %d order by TestID",ptheApp->m_testID);
if(!m_recordset.Open(AFX_DB_USE_DEFAULT_TYPE,strSQL)){
MessageBox("打开数据库失败!","数据库错误",MB_OK);
return ;
}

//创建表格
wordHandle.CreateTable(9, 4);
wordHandle.SetTableFont(1, 1, 9, 4, _T("宋体"), 12);
wordHandle.SetTableFormat(1, 1, 9, 4, wdAlignParagraphCenter, wdCellAlignVerticalCenter);
wordHandle.SetTablePadding();
wordHandle.WriteCell(1, 1, _T("XX型号"));
wordHandle.WriteCell(1, 2, m_recordset.m_CableGG);
wordHandle.WriteCell(1, 3, _T("XX类型"));
wordHandle.WriteCell(1, 4, m_recordset.m_AATT);
wordHandle.WriteCell(2, 1, _T("测试长度"));
wordHandle.WriteCell(2, 2, _T("????")); ////m_testlen
wordHandle.WriteCell(2, 3, _T("XX增益"));
wordHandle.WriteCell(2, 4, m_recordset.m_AG);
wordHandle.WriteCell(3, 1, _T("纵向损耗"));
wordHandle.WriteCell(3, 2, _T("????"));
wordHandle.WriteCell(3, 3, _T("XX方向"));
wordHandle.WriteCell(3, 4, m_recordset.m_AO);
wordHandle.WriteCell(4, 1, _T("采样数量"));
wordHandle.WriteCell(4, 2, "%d", m_recordset.m_CableCD/m_recordset.m_step);
wordHandle.WriteCell(4, 3, _T("XX高度"));
wordHandle.WriteCell(4, 4, m_recordset.m_AH);
wordHandle.WriteCell(5, 1, _T("测试频率"));
wordHandle.WriteCell(5, 2, "%d", m_recordset.m_frequency);
wordHandle.WriteCell(5, 3, _T("XX距离"));
wordHandle.WriteCell(5, 4, m_recordset.m_AD);
wordHandle.WriteCell(6, 1, _T("测试日期"));
wordHandle.WriteCell(6, 2, m_recordset.m_TestDate.Format("%Y-%m-%d %H:%M:%S"));
wordHandle.WriteCell(6, 3, _T("测试人员"));
wordHandle.WriteCell(6, 4, m_recordset.m_Tester);
wordHandle.WriteCell(7, 1, _T("测试仪器"));
wordHandle.WriteCell(7, 2, _T("????"));
wordHandle.WriteCell(7, 3, _T("测试温度"));
wordHandle.WriteCell(7, 4, "%2.1f", m_recordset.m_temperature);
wordHandle.WriteCell(8, 1, _T("耦合损耗"));
wordHandle.WriteCell(8, 2, _T("????"));
wordHandle.WriteCell(8, 3, _T("XXX值"));
wordHandle.WriteCell(8, 4, _T("????"));
wordHandle.WriteCell(9, 1, _T("XXX值"));
wordHandle.WriteCell(9, 2, _T("????"));
wordHandle.WriteCell(9, 3, _T("XXX值"));
wordHandle.WriteCell(9, 4, _T("????"));
m_recordset.Close();

//屏幕截图保存
CString bigChart = _T("\\big.bmp");
CString smallChart = _T("\\small.bmp");
m_static.Save(strAppPath+bigChart);
m_astatic.save(strAppPath+smallChart);

wordHandle.AddParagraph();
wordHandle.SetParagraphFormat(wdAlignParagraphCenter);
wordHandle.AddPicture(strAppPath+bigChart);
wordHandle.AddPicture(strAppPath+smallChart);
wordHandle.ShowWord(TRUE); //设置可见
}

现在贴上一个比较低级的一个demo,VS2010创建,DAO连接ACCESS数据库,生成word文档:http://download.csdn.net/detail/cai843383655/9402675

下面简要说一下如何通过MSWORD.OLB生成可操作word文档的接口文件,即上述的msword.hmsword.cpp


1. vs2010创建一个项目,打开类向导

C++操作word:插入文字、图片、表格,设置样式字体


2. 右上角添加类,下拉框选择类型库中的MFC类

C++操作word:插入文字、图片、表格,设置样式字体


3. 文件来源添加类,选择文件位置:C:\Program Files (x86)\Microsoft Office\Office14

C++操作word:插入文字、图片、表格,设置样式字体

C++操作word:插入文字、图片、表格,设置样式字体


4.生成类,可以根据自己需要只选择其中几项

C++操作word:插入文字、图片、表格,设置样式字体

C++操作word:插入文字、图片、表格,设置样式字体

C++操作word:插入文字、图片、表格,设置样式字体



注:

用VS2010生成的类不在一个文件中,用vc++6.0可把所有类集中在同一个文件中(头文件与目标文件)。上述的msword.h与msword.cpp是在VC++6.0中导入生成的,其它版本没有测试过。

另外,用上述同样方法可以操作excel文件,只不过导入的excel.exe。其它office文件类似,下面是别人的一些总结,搬运过来。

Office 版本和类型

类型库文件

Office 版本和类型

类型库文件

Access 97 Msacc8.olb PowerPoint 2000 Msppt9.olb
Jet Database 3.5 DAO350.dll Word 2000 Msword9.olb
Binder 97 Msbdr8.olb Access 2002 Msacc.olb
Excel 97 Excel8.olb Excel 2002 Excel.exe
Graph 97 Graph8.olb Graph 2002 Graph.exe
Office 97 Mso97.dll Office 2002 MSO.dll
Outlook 97 Msoutl97.olb Outlook 2002 MSOutl.olb
PowerPoint 97 Msppt8.olb PowerPoint 2002 MSPpt.olb
Word 97 Msword8.olb Word 2002 MSWord.olb
Access 2000 Msacc9.olb Office Access 2003 Msacc.olb
Jet Database 3.51 DAO360.dll Office Excel 2003 Excel.exe
Binder 2000 Msbdr9.olb Graph 2003 Graph.exe
Excel 2000 Excel9.olb Office 2003 MSO.dll
Graph 2000 Graph9.olb Office Outlook 2003 MSOutl.olb
Office 2000 Mso9.dll Office PowerPoint 2003 MSPpt.olb
Outlook 2000 Msoutl9.olb Office Word 2003 MSWord.olb



附地址:http://blog.csdn.net/wowolook/article/details/8509664