MFC创建Word文档,进行插入表格、图片操作

VS2013+office2013实现Word文档的创建,以及实现插入表格、图片的操作,在数据保存完毕后会弹出窗口选择保存路径,可以保存成doc和PDF的格式。


首先在界面上添加一个保存按钮,然后添加点击事件响应函数OnBnClickedButton1(),函数里面调用报表生成函数OnMakeExport(),OnMakeExport()函数代码如下,对象的创建放到了CTest002Dlg.h文件里。

BOOL CTest002Dlg::OnMakeExport()
{
	// 	CApplication wordApp;
	// 	CDocuments wordDocs;
	// 	CDocument0 wordDoc;
	// 	CSelection wordSelection;
	// 	CRange wordRange;
	// 	CTables0 wordTables;
	// 	CTable0 wordTable;
	// 	CCell wordCell;
	// 	CCells wordCells;
	// 	//Paragraphs wordParagraphs;
	// 	//Paragraph wordParagraph;
	// 	CFont0 wordFont;
	// 	CShading wordShading;
	//
	/*int nRow = 0;*/
	//
	COleVariant vTrue((short)TRUE),
		vFalse((short)FALSE),
		vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	CComVariant defaultBehavior(1), AutoFitBehavior(0);

	if (!AfxOleInit())
	{
		AfxMessageBox(_T("Initialize COM context failed!"));
		return FALSE;
	}
	//创建word application实例
	if (!wordApp.CreateDispatch(_T("Word.Application"), NULL))
	{
		AfxMessageBox(_T("启动Word程序失败!"));
		return FALSE;
	}
	//wordApp.SetVisible(TRUE);//make visible
	wordApp.put_Visible(TRUE);
	wordApp.Activate();//激活
	wordDocs = wordApp.get_Documents();
	//wordDocs = wordApp.GetDocuments();//get documents object
	CString strDocTemplate;
	CString strPath;
	wchar_t szFullPath[_MAX_PATH];
	::GetModuleFileName(NULL, szFullPath, _MAX_PATH);
	strDocTemplate.Format(_T("%s"), szFullPath);
	int nPos = strDocTemplate.ReverseFind('""');
	strDocTemplate = strDocTemplate.Left(nPos);
	strPath = strDocTemplate;
	TRACE("%s/n", strDocTemplate);

	CComVariant tpl(_T("")), Visble, DocType(0), NewTemplate(false);
	wordDoc = wordDocs.Add(&tpl, &NewTemplate, &DocType, &Visble);//Add(&tpl, &NewTemplate, &DocType, &Visble); 
	wordSelection = wordApp.get_Selection();//.GetSelection()
	//wordTables.AttachDispatch(wordDoc.GetTables());
	wordTables = wordDoc.get_Tables();//.GetTables();
	//wordParagraphs = wordDoc.GetParagraphs();
	//wordParagraph=wordParagraphs.GetLast();
	//wordRange=wordParagraph.GetRange();
	//wordSelection.EndKey(COleVariant((short)6),COleVariant((short)0));
	//move insertion point to the end of the story
	/*
	wdUnits:
	wdCharacter=1
	wdWord=2
	wdSentence=3
	wdParagraph=4
	wdSection=8
	wdStory=6
	wdCell=12
	wdColumn=9
	wdRow=10
	wdTable=15
	wdMovementType:

	wdMove=0
	wdExtend=1
	*/
	//move to end of story
	wordSelection.EndOf(COleVariant((short)6), COleVariant((short)0));

	//wordApp.get_Version();
	wordApp.put_Visible(FALSE);
	//1.1 RxLev Full 
	wordSelection.TypeText(_T("1. 统计报告"));
	wordSelection.HomeKey(&CComVariant(5), &CComVariant(1));
	//Format the line with selection
	wordFont = wordSelection.get_Font();//.GetFont();
	wordFont.put_Bold(9999998);//.SetBold(9999998);//wdToggle
	wordSelection.EndOf(&CComVariant(5), &CComVariant(0));
	wordSelection.TypeParagraph();
	wordSelection.TypeText(_T("(1.1). 分段统计"));
	wordSelection.TypeParagraph();
	wordFont.put_Bold(9999998);//wdToggle
	wordRange = wordSelection.get_Range();//.GetRange();
	//add table
	//nRow=m_nRange1+1;
	wordTable = wordTables.Add(wordRange, 5/*row*/, 4/*column*/, &defaultBehavior, &AutoFitBehavior);
	wordRange = wordTable.get_Range();//.GetRange();
	//wordRange.MoveEnd(COleVariant((short)15),COleVariant((short)1));
	//wordRange.Select();
	//move end of table
	//wordSelection.EndOf(COleVariant((short)15),COleVariant((short)0));
	//insert rows
	//wordSelection.InsertRowsBelow(COleVariant((short)5));
	//选择第一个单元,进而选择第一行进行格式化
	wordCell = wordTable.Cell(1, 1);
	wordCell.Select();
	//select the row with current selection
	wordSelection.EndKey(&CComVariant(10), &CComVariant(1));
	//Format the row with selection
	//wordFont = wordSelection.GetFont();
	wordFont.put_Bold(9999998);//.SetBold(9999998);//wdToggle
	wordCells = wordSelection.get_Cells();//.GetCells();
	wordShading = wordCells.get_Shading();//.GetShading();
	wordShading.put_Texture(0);//.SetTexture(0);
	wordShading.put_BackgroundPatternColor(14737632);//.SetBackgroundPatternColor(14737632);//15987699 14737632 adColorBlue
	wordShading.put_ForegroundPatternColor(-16777216);//.SetForegroundPatternColor(-16777216);//-16777216 wdColorAutomatic
	//move to end of table
	//wordSelection.EndOf(COleVariant((short)15),COleVariant((short)0));
	//wordParagraph=wordParagraphs.GetLast();
	//wordRange=wordParagraph.GetRange();
	//wordRange.MoveEnd(COleVariant((short)4),COleVariant((short)1));     
	//wordRange.SetText("Test");
	//wordSelection=wordApp.GetSelection();
	//wordSelection.MoveEnd(COleVariant((short)6),COleVariant((short)1));
	
	wordCell = wordTable.Cell(1, 1);
	wordCell.Select();
	wordSelection.TypeText(_T("统计项目"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("采样"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("百分比"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("累计百分比"));
	// 	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	// 	wordSelection.TypeText(_T("经济学"));
	// 	wordSelection.MoveRight(&CComVariant(12), &CComVariant(4), &CComVariant(0));
	// 	wordSelection.TypeText(_T("政治学"));

	wordSelection.EndOf(COleVariant((short)6), COleVariant((short)0));
	wordSelection.TypeParagraph();
	wordSelection.TypeText(_T("(1.2). 分段统计"));
	wordSelection.HomeKey(&CComVariant(5), &CComVariant(1));
	//Format the line with selection
	wordFont = wordSelection.get_Font();//.GetFont();
	wordFont.put_Bold(9999998);//.SetBold(9999998);//wdToggle
	wordSelection.EndOf(&CComVariant(5), &CComVariant(0));
	wordSelection.TypeParagraph();
	wordFont.put_Bold(9999998);//wdToggle
	wordRange = wordSelection.get_Range();//.GetRange();
	//add table
	//nRow=m_nRange1+1;
	wordTable = wordTables.Add(wordRange, 5/*row*/, 4/*column*/, &defaultBehavior, &AutoFitBehavior);
	wordRange = wordTable.get_Range();
	//选择第一个单元,进而选择第一行进行格式化
	wordCell = wordTable.Cell(1, 1);
	wordCell.Select();
	//select the row with current selection
	wordSelection.EndKey(&CComVariant(10), &CComVariant(1));
	//Format the row with selection
	wordFont = wordSelection.get_Font();
	wordFont.put_Bold(9999998);
	wordCells = wordSelection.get_Cells();
	wordShading = wordCells.get_Shading();
	wordShading.put_Texture(0);
	wordShading.put_BackgroundPatternColor(14737632);//15987699
	wordShading.put_ForegroundPatternColor(-16777216);
	wordCell = wordTable.Cell(1, 1);
	wordCell.Select();
	wordSelection.TypeText(_T("Range"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("Samples"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("Percentage"));
	wordSelection.MoveRight(&CComVariant(12), &CComVariant(1), &CComVariant(0));
	wordSelection.TypeText(_T("Calculation"));
	wordSelection.EndOf(COleVariant((short)6), COleVariant((short)0));
	//
	//Save document as report
	//获取当前系统时间
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	CString strReport;


	//设置文件名及保存路径
	// 	CString road;
	// 	road = CString("F:\\");
	strReport.Format(_T("%d年-%d月-%d日 %d-%d-%d 报告"), sysTime.wYear, sysTime.wMonth,
		sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
	strReport = strPath + """" + strReport;
	/*	road.Append(strReport);*/
	/*	strReport = road;*/

	//插入图片
	CString   filePath = _T("C:\\Users\\admin\\Desktop\\20.jpg");
	CString   filePath1 = _T("C:\\Users\\admin\\Desktop\\123.jpg");
	_OnInsertPic(filePath);
	_OnInsertPic(filePath1);

	//保存doc文档

	const int wdNULL = 0;
	CFileDialog FileDlg(FALSE, L"doc", strReport);
	FileDlg.m_ofn.lpstrFilter = L"Text Files(*doc)\0*.doc\0Text Files(*pdf)\0*.pdf\0All Files(*.*)\0*.*\0\0";
	CString TypeOfFile;
	if (IDOK == FileDlg.DoModal())
	{
		strReport = FileDlg.GetPathName();
		CString lastname = strReport.Right(3);
		if (lastname == "doc")
		{
			wordDoc.SaveAs(COleVariant(strReport), //FileName
				COleVariant((short)wdFormatDocument), //FileFormat  参数为wdFormatDocument时生成doc文档
				COleVariant((short)FALSE), //LockComments
				COleVariant(_T("")), //Password
				COleVariant((short)FALSE), //AddToRecentFiles
				COleVariant(_T("")), //WritePassword
				COleVariant((short)FALSE), //ReadOnlyRecommended
				COleVariant((short)FALSE), //EmbedTrueTypeFonts
				COleVariant((short)FALSE), //SaveNativePictureFormat
				COleVariant((short)FALSE), //SaveFormsData
				COleVariant((short)FALSE), //SaveAsAOCELetter
				COleVariant((short)wdNULL), //Encoding
				COleVariant((short)FALSE), //InsertLineBreaks
				COleVariant((short)FALSE), //AllowSubstutitions,
				COleVariant((short)wdNULL), //LineEnding
				COleVariant((short)wdNULL));//AddBiDiMarks
		}
		else
		{
			wordDoc.SaveAs(COleVariant(strReport), //FileName
				COleVariant((short)wdFormatPDF), //FileFormat  参数为wdFormatDocument时生成doc文档
				COleVariant((short)FALSE), //LockComments
				COleVariant(_T("")), //Password
				COleVariant((short)FALSE), //AddToRecentFiles
				COleVariant(_T("")), //WritePassword
				COleVariant((short)FALSE), //ReadOnlyRecommended
				COleVariant((short)FALSE), //EmbedTrueTypeFonts
				COleVariant((short)FALSE), //SaveNativePictureFormat
				COleVariant((short)FALSE), //SaveFormsData
				COleVariant((short)FALSE), //SaveAsAOCELetter
				COleVariant((short)wdNULL), //Encoding
				COleVariant((short)FALSE), //InsertLineBreaks
				COleVariant((short)FALSE), //AllowSubstutitions,
				COleVariant((short)wdNULL), //LineEnding
				COleVariant((short)wdNULL));//AddBiDiMarks
		}
		wordApp.put_Visible(FALSE);//文档自动关闭
		/*File = (CFile)wordApp;*/
		wordFont.ReleaseDispatch();
		wordCells.ReleaseDispatch();
		wordShading.ReleaseDispatch();
		wordTable.ReleaseDispatch();
		wordTables.ReleaseDispatch();
		wordRange.ReleaseDispatch();
		wordSelection.ReleaseDispatch();
		wordDoc.RecheckSmartTags();
		wordDocs.ReleaseDispatch();

		COleVariant vTrue1((short)TRUE),
			vFalse((short)FALSE),
			vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
		wordDoc.Close(vFalse,    // SaveChanges.
			vTrue1,            // OriginalFormat.
			vFalse            // RouteDocument.
			);
		wordApp.Quit(vFalse,    // SaveChanges.
			vTrue1,            // OriginalFormat.
			vFalse            // RouteDocument.
			);
		wordApp.ReleaseDispatch();
	}
	// //	    第二个参数值列表:
	// // 	wdFormatDocument 0 Microsoft Office Word 格式。
	// // 		wdFormatDOSText 4 Microsoft DOS 文本格式。
	// // 		wdFormatDOSTextLineBreaks 5 Microsoft DOS 文本格式,并且保留换行符。
	// // 		wdFormatEncodedText 7 编码文本格式。
	// // 		wdFormatFilteredHTML 10 筛选的 HTML 格式。
	// // 		wdFormatHTML 8 标准 HTML 格式。
	// // 		wdFormatRTF 6 RTF 格式。
	// // 		wdFormatTemplate 1 Word 模板格式。
	// // 		wdFormatText 2 Microsoft Windows 文本格式。
	// // 		wdFormatTextLineBreaks 3 Windows 文本格式,并且保留换行符。
	// // 		wdFormatUnicodeText 7 Unicode 文本格式。
	// // 		wdFormatWebArchive 9 Web 档案格式。
	// // 		wdFormatXML 11 可扩展标记语言(XML) 格式。
	// // 		wdFormatDocument97 0 Microsoft Word 97 文档格式。
	// // 		wdFormatDocumentDefault 16 Word 默认文档文件格式。对于 Microsoft Office Word 2007,这是 DOCX 格式。
	// // 		wdFormatPDF 17 PDF 格式。
	// // 		wdFormatTemplate97 1 Word 97 模板格式。
	// // 		wdFormatXMLDocument 12 XML 文档格式。
	// // 		wdFormatXMLDocumentMacroEnabled 13 启用了宏的 XML 文档格式。
	// // 		wdFormatXMLTemplate 14 XML 模板格式。
	// // 		wdFormatXMLTemplateMacroEnabled 15 启用了宏的 XML 模板格式。
	// // 		wdFormatXPS 18 XPS 格式。
	return TRUE;
}

插入图片函数代码如下:

void CTest002Dlg::_OnInsertPic(CString filepath)
{
	//插入图片
	CSelection sel;
	CnlineShapes ishaps;
	CnlineShape ishap;

	sel = wordApp.get_Selection();
	sel.TypeParagraph();

	COleVariant vTrue1((short)TRUE),
		vFalse1((short)FALSE),
		vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	ishaps = sel.get_InlineShapes();
	ishap = ishaps.AddPicture(filepath, vFalse1, vTrue1, vOptional);
	//设置图片宽度和高度
	ishap.put_Width(64);
	ishap.put_Height(51);
	sel.TypeParagraph();
	sel.ReleaseDispatch();
}
OLB文件下载链接 下载OLB文件实现MFC与office的连接。

猜你喜欢

转载自blog.csdn.net/kai69/article/details/80742661