MFC从数据库里导出excel文档


void CPctoolDlg::OnUserExcell() 
{
	if(!m_ExlApp.CreateDispatch("Excel.Application",NULL)) 
	{ 
		AfxMessageBox("创建Excel服务失败!"); 
		return; 
	} 
	//m_ExlApp.SetVisible(TRUE);
	CString TempPath="XXX.xls"; 
	m_ExlBooks.AttachDispatch(m_ExlApp.GetWorkbooks(),TRUE); 
	m_ExlBook.AttachDispatch(m_ExlBooks.Add((_variant_t)TempPath),TRUE);//加载EXCEL模板 
	m_ExlSheets.AttachDispatch(m_ExlBook.GetSheets(),TRUE);//加载Sheet页面 

	//添加新的Sheet页面 
	//m_ExlSheets.Add(vtMissing,vtMissing,_variant_t((long)1),vtMissing);	
	//删除第二个Sheet页面 
	//m_ExlSheet.AttachDispatch(m_ExlSheets.GetItem(_variant_t((long)2)),TRUE); 
	//m_ExlSheet.Delete();	
	//把第一个Sheet页面的名字改变为TestSheet 
	m_ExlSheet.AttachDispatch(m_ExlSheets.GetItem(_variant_t((long)1)),TRUE); 
	//m_ExlSheet.SetName("TestSheet");

	m_ExlRge.AttachDispatch(m_ExlSheet.GetCells(),TRUE);//加载所有单元格 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)1),_variant_t("Bracode")); 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)2),_variant_t("SN")); 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)3),_variant_t("MAC")); 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)4),_variant_t("TN")); 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)5),_variant_t("Result")); 
	m_ExlRge.SetItem(_variant_t((long)1),_variant_t((long)6),_variant_t("Time")); 

	pDataBase->Executesql("select * from MB328");
	int i = 2;
	while(!pDataBase->pRst->rsEOF)
	{
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)1),(_variant_t)pDataBase->pRst->GetCollect("Barcode"));
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)2),(_variant_t)pDataBase->pRst->GetCollect("SN"));
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)3),(_variant_t)pDataBase->pRst->GetCollect("MAC"));
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)4),(_variant_t)pDataBase->pRst->GetCollect("TN"));
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)5),(_variant_t)pDataBase->pRst->GetCollect("Result"));
	    m_ExlRge.SetItem(_variant_t((long)i),_variant_t((long)6),(_variant_t)pDataBase->pRst->GetCollect("Time"));
	    pDataBase->pRst->MoveNext();
	    i++;
	}
	

	//m_ExlBook.SetSaved(true);
	m_ExlApp.SetVisible(TRUE);
	m_ExlRge.ReleaseDispatch(); 
	m_ExlSheet.ReleaseDispatch(); 
	m_ExlSheets.ReleaseDispatch(); 
	m_ExlBook.ReleaseDispatch(); 
	m_ExlBooks.ReleaseDispatch(); 
	m_ExlApp.ReleaseDispatch(); 
	m_ExlApp.Quit();
}	

以上是主要的代码,前期准备工作是:

1.首先你需要有一个数据库相关的类DataBase,这里pDataBase就是指向这个类对象,里面封装了一系列关于数据库的操作。

2.利用MFC的类向导添加excell相关的6个类,这时excel.cpp和execel.h会自动添加到工程目录里,然后在在头文件处添加一下代码

#include "excel.h
#include "comdef.h

Range        m_ExlRge; 
_Worksheet   m_ExlSheet; 
Worksheets   m_ExlSheets; 
_Workbook    m_ExlBook; 
Workbooks    m_ExlBooks; 
_Application m_ExlApp;





你可能感兴趣的:(MFC从数据库里导出excel文档)