在需要对EXCEL表进行操作的类中添加以下头文件:若出现大量错误将其放入stdafx.h中
cpp
#include "resource.h" // 主符号
#include "CWorkbook.h" //单个工作簿
#include "CRange.h" //区域类,对Excel大部分操作都需要
#include "CWorkbooks.h" //管理所有工作簿
#include "CApplication.h" //Excel应用程序类,管理整个Excel应用
在类中添加以下变量定义:
cpp
//定义Excel中需要的工作簿以及工作表等
CApplication m_App;
CWorkbooks m_Books;
CWorkbook m_Book;
CWorksheets m_Sheets;
CWorksheet m_Sheet;
CRange m_Range;
然后就可以封装对应函数,以下为打开Excel表的例子,一般包括Excel的读写:
cpp
//打开Excel表
int CExcel_TestApp::OpenExcel(CString FileName)
{
HRESULT Hr;//HRESULT函数返回值
Hr = CoInitialize(NULL);//CoInitialize告诉Windows以单线程方式创建com对象
if (FAILED(Hr))
{
AfxMessageBox(_T("调用函数失败!"));
}
LPDISPATCH LpDisp;
COleVariant CovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if (!m_App.CreateDispatch(_T("Excel.Application"), NULL))
{
AfxMessageBox(_T("无法启动EXCEL服务器!"));
return 0;
}
m_Books.AttachDispatch(m_App.get_Workbooks);//得到工作簿
LpDisp = m_Books.Open(FileName, CovOptional, CovOptional, CovOptional, CovOptional,
CovOptional, CovOptional, CovOptional, CovOptional, CovOptional,
CovOptional, CovOptional, CovOptional, CovOptional);
m_Book.AttachDispatch(LpDisp);//得到单个工作簿
m_Sheets.AttachDispatch(m_Book.get_Worksheets);//得到工作簿对应的工作表
LpDisp = m_Book.get_ActiveSheet();//得到当前活跃的工作表
m_Sheet.AttachDispatch(LpDisp);//获取到表
return 1;
}
若运行出错,将导入的所有包含#import "C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE" no_namespace头文件中的注释,将CRange.h中的DialogBox改为_DialogBox;
cpp
int MFC_OpenExcel::OpenExcel(CString FileName)
{
HRESULT Hr;//HRESULT函数返回值
Hr = CoInitialize(NULL);//CoInitialize告诉Windows以单线程方式创建com对象
if (FAILED(Hr))
{
AfxMessageBox(_T("调用函数失败!"));
}
LPDISPATCH LpDisp;
COleVariant CovOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if (!m_App.CreateDispatch(_T("Excel.Application"), NULL))
{
AfxMessageBox(_T("无法启动EXCEL服务器!"));
return 0;
}
m_Books=m_App.get_Workbooks();//得到工作簿
LpDisp = m_Books.Open(FileName, CovOptional, CovOptional, CovOptional, CovOptional,
CovOptional, CovOptional, CovOptional, CovOptional, CovOptional,
CovOptional, CovOptional, CovOptional, CovOptional, CovOptional);
m_Book.AttachDispatch(LpDisp);//得到单个工作簿
m_Sheets=m_Book.get_Worksheets();//得到工作簿对应的工作表
LpDisp = m_Book.get_ActiveSheet();//得到当前活跃的工作表
m_Sheet.AttachDispatch(LpDisp);//获取到表
return 1;
}