2008年(909)
分类:
2008-05-06 22:10:40
下载源代码
用EXCEL作为报表的输出方式还是比较常用的方式,这样可以充分利用EXCEL的强大的编辑功能,以及打印功能。而采用模板方式是比较好的方法,首先在EXCEL中制作模板,然后在生成报表时调用模板。这样能方便的生成我们需要的报表。这里主要描述如何加载模板和添加每页报表。代码如下:
void CExceltestDlg::OnButton1() { // TODO: Add your control notification handler code here _Application ExcelApp; Workbooks wbsMyBooks; _Workbook wbMyBook; Worksheets wssMysheets; _Worksheet wsMysheet; Range rgMyRge; //创建Excel 2000服务器(启动Excel) if (!ExcelApp.CreateDispatch("Excel.Application",NULL)) { AfxMessageBox("创建Excel服务失败!"); exit(1); } ExcelApp.SetVisible(false); //利用模板文件建立新文档 char path[MAX_PATH]; GetCurrentDirectory(MAX_PATH,path); CString strPath = path; strPath = "\\template1"; wbsMyBooks.AttachDispatch(ExcelApp.GetWorkbooks(),true); wbMyBook.AttachDispatch(wbsMyBooks.Add(_variant_t(strPath))); //得到Worksheets wssMysheets.AttachDispatch(wbMyBook.GetWorksheets(),true); //得到sheet1 wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("sheet1")),true); //添加模板个数 for(int i=0;i<4;i ){ wsMysheet.Copy(vtMissing,_variant_t(wsMysheet)); } CString str1; wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("sheet1")),true); str1 = "第1页"; wsMysheet.SetName(str1); for(i=0;i结果得到如下图://此地方该显示时缺少两项 wsMysheet = wsMysheet.GetNext(); str1.Format("第%d页",i 2); wsMysheet.SetName(str1); } wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("第1页")),true); //得到全部Cells,此时,rgMyRge是cells的集合 rgMyRge.AttachDispatch(wsMysheet.GetCells(),true); //设置1行1列的单元的值 CString str=_TEXT("21:12"); rgMyRge.SetItem(_variant_t((long)7),_variant_t((long)3),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)9),_variant_t((long)3),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)7),_variant_t((long)4),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)8),_variant_t((long)4),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)9),_variant_t((long)4),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)10),_variant_t((long)4),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)11),_variant_t((long)4),_variant_t(str)); rgMyRge.SetItem(_variant_t((long)12),_variant_t((long)4),_variant_t(str)); //将表格保存 strPath = path; strPath = "\\ylhexcel.xls"; wsMysheet.SaveAs(strPath,vtMissing,vtMissing,vtMissing,vtMissing, vtMissing,vtMissing,vtMissing,vtMissing); ExcelApp.SetVisible(true); wbMyBook.PrintPreview(_variant_t(false)); //释放对象 rgMyRge.ReleaseDispatch(); wsMysheet.ReleaseDispatch(); wssMysheets.ReleaseDispatch(); wbMyBook.ReleaseDispatch(); wbsMyBooks.ReleaseDispatch(); ExcelApp.ReleaseDispatch(); }