分类: C/C++
2008-08-01 17:03:06
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(); }