VS2013+office2013實現Word文檔的創建,以及實現插入表格、圖片的操作,在數據保存完畢後會彈出窗口選擇保存路徑,可以保存成doc和PDF的格式。
首先在界面上添加一個保存按鈕,然後添加點擊事件響應函數OnBnClickedButton1(),函數裏面調用報表生成函數OnMakeExport(),OnMakeExport()函數代碼如下,對象的創建放到了CTest002Dlg.h文件裏。
OLB文件下載鏈接 下載OLB文件實現MFC與office的連接。
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();
}