在 Visual Studio 2010 中使用 C++ 操作 Office 2010

1、在VC中新建一控制台程序,选支持MFC
2、项目 - 类向导 - 添加类(右侧小箭头) - 类型库中的MFC类
3、选择文件 C:\Program Files\Microsoft Office\Office14\MSWORD.OLB
4、添加 _Application、Documents、_Document、Range
5、在程序中引用刚才生成的头文件
#include "CApplication.h"
#include "CDocument0.h"
#include "CDocuments.h"
#include "CRange.h"

6、此时编译会报错:
error C2786: “BOOL (HDC,int,int,int,int)”: __uuidof 的操作数无效
解决方法:
A:
修改上面四个文件中的
#import "C:\\Program Files\\Microsoft Office\\Office14\\MSWORD.OLB" no_namespace
为:
#import "C:\\Program Files\\Microsoft Office\\Office14\\MSWORD.OLB" no_namespace raw_interfaces_only \
	rename("FindText","_FindText") \
	rename("Rectangle","_Rectangle") \
	rename("ExitWindows","_ExitWindows")
B:
直接将上面四个文件中的
#import "C:\\Program Files\\Microsoft Office\\Office14\\MSWORD.OLB" no_namespace
这一行删除

再次编译,错误消失

7、测试程序
void testWordInterface()
{
	CString csFilePath = L"C:\\Users\\vm\\Desktop\\aaa.doc";

	CoInitialize(NULL);//初始化COM,与最后一行CoUninitialize对应
	
	CApplication app;
	CDocuments docs;
	CDocument0 doc;
	COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
	COleVariant varZero((short)0); 
	COleVariant varTrue(short(1),VT_BOOL); 
	COleVariant varFalse(short(0),VT_BOOL);

	if(!app.CreateDispatch(_T("word.application"))) //启动WORD
	{
		_tprintf(_T("OFFICE has not installed.\n"));
		return;
	}

	_tprintf(_T("WORD is running.\n"));
	app.put_Visible(FALSE); //设置WORD可见

	docs = app.get_Documents();
	doc = docs.Open(COleVariant(csFilePath),varFalse,varTrue,varFalse,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional,covOptional);

	CString csName = doc.get_Name();
	_tprintf(csName);

	_tprintf(_T("WORD will exit."));
	doc.Close(varFalse, covOptional, covOptional);
	doc.ReleaseDispatch();
	docs.ReleaseDispatch();

	//调用Quit退出WORD应用程序。不调用的话WORD还在运行
	app.Quit(new CComVariant(FALSE),new CComVariant(),new CComVariant());
	app.ReleaseDispatch();   //释放对象指针。切记,必须调用

	CoUninitialize();//对应CoInitialize
}
//例子1
void CMyWordDlg::OnBnClickedButton1()
{
 CoInitialize(NULL);//初始化COM,与最后一行CoUninitialize对应
//CPageSetup pagesetup=doc.get_PageSetup();//页面设置相关,没用到
 CApplication app;
 if(!app.CreateDispatch(_T("word.application"))) //启动WORD
 {
  AfxMessageBox(_T("居然你连OFFICE都没有安装吗?"));
  return;
 }
 AfxMessageBox(_T("WORD 已经运行启动啦,你可以用Ctrl+Alt+Del查看"));
 app.put_Visible(TRUE); //设置WORD可见。
 
 CDocuments docs = app.get_Documents();
 docs.Add(new CComVariant(_T("")),new CComVariant(FALSE),new CComVariant(0),new CComVariant());//创建新文档
 
 AfxMessageBox(_T("下面,程序要向WORD发送字符啦"));
 CSelection sel=app.get_Selection();//Selection表示输入点,即光标闪烁的那个地方
 CFont0 font =sel.get_Font();
 font.put_Name(_T("宋体"));//设置字体
 font.put_Size(14);
 font.put_Color(WdColor::wdColorGreen);
 font.put_Bold(1);
 sel.TypeText(_T("HELLO\r\n大家好呀"));//调用函数Selection::TypeText 向WORD发送字符
 font.ReleaseDispatch();//【注】【意】所有东西用完之后一定要ReleaseDispatch,否则报错;不过最好像例子2中,在最后集中ReleaseDispatch

 //插入表格
 CDocument0 doc = app.get_ActiveDocument();//活动文档
 CTables0 tables = doc.get_Tables();
 tables.Add(sel.get_Range(), 7,11,  new CComVariant(),new  CComVariant());//插入表
 CTable0 table=tables.Item(1);
 CBorders borders=table.get_Borders();//设置表格边框
 borders.put_InsideLineStyle(WdLineStyle::wdLineStyleSingle);
 borders.put_OutsideLineStyle(WdLineStyle::wdLineStyleDouble);
 //borders.put_OutsideLineWidth(WdLineWidth::wdLineWidth075pt);
 borders.ReleaseDispatch();
 sel.TypeText(_T("test1"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test2"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test3"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test4"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test5"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test6"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test7"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test8"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test9"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test10"));
 sel.MoveRight(COleVariant((short)1),COleVariant(short(1)),COleVariant(short(0)));
 sel.TypeText(_T("Test11"));
 int i=0,j=0;
 for(i=2;i<7;i+=2)
 {
  CCell c1=table.Cell(i,1);
  CCell c2=table.Cell(i+1,1);
  c1.Merge(c2);//合并单元格
  c1.ReleaseDispatch();
  c2.ReleaseDispatch();
 }
 CCell c;
 CString strName[3];
 strName[0] = "yingkou";
 strName[1] ="zyq654321";
 strName[2] ="iwaswzq";
 for(j=0,i=0;i<3;++i,j+=2)
 {
  c=table.Cell(j+2,1);
  c.Select();
  CCells cs=sel.get_Cells();
  cs.put_VerticalAlignment(WdVerticalAlignment::wdAlignVerticalCenter);
  sel.TypeText(strName[i]);
  sel.MoveDown(COleVariant((short)5),COleVariant(short(1)),COleVariant(short(0)));
  cs.ReleaseDispatch();
  c.ReleaseDispatch();
 }
 c=table.Cell(7, 2);
 c.Select();
 CString strData[6];
 strData[0]="111";
 strData[1]="222";
 strData[2]="333";
 for(i=0,j=0;i<6;++i,++j)
 {
  if(i%2==0)
   j=0;
  sel.TypeText(strData[j]);
  sel.MoveUp(COleVariant((short)5),COleVariant(short(1)),COleVariant(short(0)));
 }
 c.ReleaseDispatch();
 
 c=table.Cell(7, 2);
 c.Select();//选中最后一行
 sel.MoveDown(COleVariant((short)5),COleVariant(short(1)),COleVariant(short(0)));//下移,输入点到页末
 c.ReleaseDispatch();
 CComVariant pageBreak = CComVariant(WdBreakType::wdPageBreak);
 sel.InsertBreak(&pageBreak);//插入分页符
 
 sel.TypeText(_T("this is the 2nd page!\r\n"));
 
 //设置页眉页脚
 CWindow0 win = doc.get_ActiveWindow();//窗口Window对象
 CPane pane = win.get_ActivePane();//当前活动Pane窗格对象
 CView0 view = pane.get_View();//View视图对象
 view.put_Type(WdViewType::wdPrintView);//设置视图类型:打印、打印预览、阅读...
 view.put_SeekView(WdSeekView::wdSeekCurrentPageHeader);//页眉视图
 CHeaderFooter headerfooter = sel.get_HeaderFooter();
 //headerfooter.put_LinkToPrevious(FALSE);//取消“与上一节相同”
 sel.TypeText(_T("this is header"));
 
 view.put_SeekView(WdSeekView::wdSeekCurrentPageFooter);//页脚视图
 sel.TypeText(_T("this is footer\r\nand here is 2nd line"));
 
 sel.TypeText(_T("第 "));
 CRange range = sel.get_Range();
 CFields fields = range.get_Fields();
 CField field = fields.Add(range, COleVariant((short)WdFieldType::wdFieldPage),COleVariant(short(0)),COleVariant(short(0)));//页码
 sel.TypeText(_T("页 共 "));
 range = sel.get_Range();
 fields = range.get_Fields();
 field = fields.Add(range, COleVariant((short)WdFieldType::wdFieldNumPages),COleVariant(short(0)),COleVariant(short(0)));//页数
 sel.TypeText(_T(" 页"));
 //下面是设置页码格式
 
 view.put_SeekView(WdSeekView::wdSeekMainDocument);//返回文字视图
 
 //插入图片,先以嵌入型图像插入,再转成浮移图像,可以移动位置,也可不转
 //据说不先按嵌入型插入的话,都会插在第一页
 range = sel.get_Range();
 COleVariant vRange;
 vRange.vt=VT_DISPATCH;
 vRange.pdispVal = range.m_lpDispatch;
 vRange.pdispVal->AddRef();
 CnlineShapes inlineshapes = doc.get_InlineShapes();
 CnlineShape inlineshape = inlineshapes.AddPicture(_T("C:\\Documents and Settings\\Administrator\\桌面\\未命名.bmp"), COleVariant((long)0), COleVariant((long)1),&vRange);
 inlineshape.put_ScaleWidth(50);
 inlineshape.put_ScaleHeight(50);
 //CShape shape = inlineshape.ConvertToShape();
 //shape.put_Width(165);
 //shape.put_Height(165);
 //shape.put_Top(200);
 //shape.put_Left(100);
 //shape.ConvertToInlineShape();
 //shape.ReleaseDispatch();
 vRange.Detach();
 sel.TypeText(_T("oh, i see the image"));
 inlineshape.ReleaseDispatch();
 inlineshapes.ReleaseDispatch();
 
 //pagenumers.ReleaseDispatch();
 field.ReleaseDispatch();
 fields.ReleaseDispatch();
 range.ReleaseDispatch();
 headerfooter.ReleaseDispatch();
 view.ReleaseDispatch();
 pane.ReleaseDispatch();
 win.ReleaseDispatch();
 
 //保存文件
 CString FileName(_T("C:\\Documents and Settings\\Administrator\\桌面\\doc.doc")); //文件名
 COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
 COleVariant varZero((short)0); 
 COleVariant varTrue(short(1),VT_BOOL); 
 COleVariant varFalse(short(0),VT_BOOL); 
 doc.SaveAs(COleVariant(FileName), varZero, varFalse,
  COleVariant(_T("")), varTrue, COleVariant(_T("")),
  varFalse, varFalse, varFalse, varFalse, varFalse,
  covOptional,covOptional,covOptional,covOptional,
  covOptional);
 AfxMessageBox(_T("WORD准备要退出啦"));
 table.ReleaseDispatch();
 tables.ReleaseDispatch();
 doc.ReleaseDispatch();
 sel.ReleaseDispatch();
 docs.ReleaseDispatch(); 
 //调用Quit退出WORD应用程序。当然不调用也可以,那样的话WORD还在运行着那
 app.Quit(new CComVariant(FALSE),new CComVariant(),new CComVariant());
 app.ReleaseDispatch();   //释放对象指针。切记,必须调用
 AfxMessageBox(_T("Step1执行完成。接着请学习Setp2"));
 CoUninitialize();//对应CoInitialize
}