MS Office 自动化编程(二)---Word文档的读写

示例一:保存至Word

经过一些了解之后,就不需要每次都将所有的接口导入工程了。可以根据需要导入,此次导入的接口为:

Application、_Document、Documents、Range。新建基于对话框的MFC工程,引入头文件,关键代码如下:

void CWordOperationDlg::OnClickedButton1()
{
	// TODO: Add your control notification handler code here
	CApplication oApp;
	CDocuments	oDocs;
	CDocument0	oDoc;

	if (!oApp.CreateDispatch(_T("Word.Application"), NULL))
	{
		AfxMessageBox(_T("启动Word程序失败!"));
		exit(1);
	}

	//查看自动化过程
	oApp.put_Visible(true);
	oDocs = oApp.get_Documents();
	COleVariant varOPt(DISP_E_PARAMNOTFOUND, VT_ERROR);
	COleVariant varStartLine, varEndLine;
	varStartLine.intVal = 2;
	varEndLine.intVal = 50;
	//添加一个新文档
	oDoc = oDocs.Add(varOPt, varOPt, varOPt, varOPt);

	//获取文档区域
	CRange range =  oDoc.Range(varStartLine, varEndLine);
	UpdateData(TRUE);
	range.put_Text(m_edit);
	//保存docx文档
	try
	{
		oDoc.SaveAs(COleVariant(_T("G:\\softwaredevelopment\\MFC_VC_Windows\\project\\TEMP.DOCX")),
			varOPt, varOPt, varOPt,
			varOPt, varOPt, varOPt,
			varOPt, varOPt, varOPt,
			varOPt, varOPt, varOPt,
			varOPt, varOPt, varOPt);
	}
	catch (COleException* e)
	{
		LPVOID lpMsg;
		::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e->m_sc,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsg, 0, NULL);
		::MessageBox(NULL, (LPCTSTR)lpMsg, _T("COM Error"), MB_OK|MB_SETFOREGROUND);
		::LocalFree(lpMsg);
	}
	catch(COleDispatchException *e)
	{
		TCHAR msg[512];
		wsprintf(msg, _T("程序运行出错'%d',系统提示信息为:\n\n%s"), e->m_scError & 0x0000FFFF,
			e->m_strDescription);
		::MessageBox(NULL, msg, _T("无法保存文件"), MB_OK|MB_SETFOREGROUND);
	}

	oDoc.Close(varOPt, varOPt, varOPt);
	oApp.Quit(varOPt, varOPt, varOPt);
}

 

运行结果:


 

示例二:Word表格操作

Word表格由表和单元格组成,对应Table和Cell对象,在以上工程中引入相应接口Table,Tables,Cell,Paragraph,Paragraphs,对表格的添加过程是先建表,再设置单元格。

在以上工程的基础上添加的关键代码:

//得到段落
	oParas = oDoc.get_Paragraphs();
	oPara = oParas.get_First();
	//得到段落区域
	oRange = oPara.get_Range();
	//设置第一段内容
	oRange.put_Text(_T("标题"));
	oPara.put_Alignment(1);

	COleVariant table_start(short(2));
	oRange = oDoc.Range(table_start, varOPt);
	//添加表格
	oTables = oDoc.get_Tables();
	oTable = oTables.Add(oRange, 3, 3, varOPt, varOPt);
	//设置表格内容
	for (int i = 1; i <= 3; i++)
	{
		for (int j = 1; j <= 3; j++)
		{
			oCell = oTable.Cell(i, j);
			oRange = oCell.get_Range();
			CString txt;
			txt.Format(_T("第%d行第%d列"),i,j);
			oRange.put_Bold(1);
			oRange.put_Text(txt);
		}
	}

操作Word结果:

 

示例二:Word报表解决方法

由以上示例可以看出对Word的操作是相当繁琐的,针对于此,利用Word的模板,只需填入关键文字,就能得到一份精美的Word文档。

同理,首先将报表的格式固定做成模板,程序向单元格填入数据。而利用“书签”就能快速定位正确的输出位置。在类型库中,对应的接口为Bookmarks、Bookmark。
1、先准备好Wrod模板

2、新建MFC基于对话框工程WordReport

3、根据需要引入类型库中的接口

关键部分代码:

void CWordReportDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	CTable0		table;
	CTables0	tables;
	if (!m_oApp.CreateDispatch(_T("Word.Application"), NULL))
	{
		AfxMessageBox(_T("Create Word service failed!"));
		exit(1);
	}

	m_oApp.put_Visible(true);
	m_oDocs = m_oApp.get_Documents();
	COleVariant vopt(DISP_E_PARAMNOTFOUND, VT_ERROR);
	COleVariant start_line, end_line;
	COleVariant dot(_T("G:\\softwaredevelopment\\MFC_VC_Windows\\project\\template.dot"));
	//使用模板建立文档
	m_oDoc = m_oDocs.Add(&dot, &vopt, &vopt, &vopt);
	//获取文档书签
	m_oBookmarks = m_oDoc.get_Bookmarks();
	//依次设置标签
	COleVariant tem1(_T("rol1"));
	m_oBookmark = m_oBookmarks.Item(&tem1);
	m_oRange = m_oBookmark.get_Range();
	//设置标题
	m_oRange.put_Text(_T("标题1"));
	
	COleVariant tem2(_T("rol2"));
	m_oBookmark = m_oBookmarks.Item(&tem2);
	m_oRange = m_oBookmark.get_Range();
	//设置标题
	m_oRange.put_Text(_T("标题2"));

	COleVariant tem3(_T("rol3"));
	m_oBookmark = m_oBookmarks.Item(&tem3);
	m_oRange = m_oBookmark.get_Range();
	//设置标题
	m_oRange.put_Text(_T("标题3"));

	//设置报表时间
	COleVariant tem4(_T("time"));
	m_oBookmark = m_oBookmarks.Item(&tem4);
	m_oRange = m_oBookmark.get_Range();
	//设置标题
	m_oRange.put_Text(_T("2012年5月20日"));

	//设置单元格内容
	tables = m_oDoc.get_Tables();
	table = tables.Item(1);
	CCell cell;
	for (int i = 2; i <= 9; i++)
	{
		for (int j = 1; j <= 3; j++)
		{
			cell = table.Cell(i,j);
			m_oRange = cell.get_Range();
			m_oRange.put_Text(_T("template"));
		}
	}
}


void CWordReportDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code here
	if (m_oDocs.m_lpDispatch == NULL)
	{
		AfxMessageBox(_T("can't preview!"));
		return;
	}
	else
	{
		if (!m_oApp.get_PrintPreview())
		{
			m_oApp.put_PrintPreview(TRUE);
		}
		else
		{
			m_oApp.put_PrintPreview(FALSE);
		}
	}
}


void CWordReportDlg::OnBnClickedButton3()
{
	// TODO: Add your control notification handler code here
	if (m_oDocs.m_lpDispatch == NULL)
	{
		AfxMessageBox(_T("Nothing! can't save!"));
		return;
	}
	else
	{
		OPENFILENAME ofn;
		TCHAR lpStrFileName[MAX_PATH] = _T("");
		ZeroMemory(&ofn, sizeof(ofn));

		ofn.lStructSize = sizeof(OPENFILENAME);
		ofn.hwndOwner = this->m_hWnd;
		ofn.lpstrFilter = _T("Word(.docx)\0*.docx\0");
		ofn.nMaxFile = MAX_PATH;
		ofn.lpstrFile = lpStrFileName;
		ofn.hInstance = AfxGetInstanceHandle();
		ofn.Flags = OPEN_EXISTING;

		COleVariant varOPt(DISP_E_PARAMNOTFOUND, VT_ERROR);
		if (GetSaveFileName(&ofn) == IDOK)
		{
			CString sFile = ofn.lpstrFile;
			try
			{
				m_oDoc.SaveAs(COleVariant(sFile),
					varOPt, varOPt, varOPt,
					varOPt, varOPt, varOPt,
					varOPt, varOPt, varOPt,
					varOPt, varOPt, varOPt,
					varOPt, varOPt, varOPt);
			}
			catch (COleException* e)
			{
				LPVOID lpMsg;
				::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
					FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e->m_sc,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsg, 0, NULL);
				::MessageBox(NULL, (LPCTSTR)lpMsg, _T("COM Error"), MB_OK|MB_SETFOREGROUND);
				::LocalFree(lpMsg);
			}
			catch(COleDispatchException *e)
			{
				TCHAR msg[512];
				wsprintf(msg, _T("程序运行出错'%d',系统提示信息为:\n\n%s"), e->m_scError & 0x0000FFFF,
					e->m_strDescription);
				::MessageBox(NULL, msg, _T("无法保存文件"), MB_OK|MB_SETFOREGROUND);
			}

			COleVariant vopt(DISP_E_PARAMNOTFOUND, VT_ERROR);
			m_oApp.Quit(COleVariant((short)true), vopt, vopt);
		}
	}
}


程序运行结果:

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值