1。在view-classwizad-autometion中点击add class-from a type library,选择execl。exe(office2003)。
2。从列表中选取_Application/_Workbook/_WorkSheet/Range/Workbooks/Worksheets 6项,确定,工程目录下会加入excel.cpp和excel.h。
3。在你的某个。h文件中添加excel相关变量,也可以直接在函数里定义:
_Application ExcelApp; //Excell 表格操作所需要的变量
Workbooks wbsMybooks;
_Workbook wbMyBook;
Worksheets wssMySheets;
_Worksheet wsMySheet;
Range MyRange;
4。为你的某个按钮单击事件添加如下代码:
void CExceltestDlg::OnOK()
{
CoUninitialize();
if(CoInitialize(NULL) != 0)
{
AfxMessageBox("初始化COM支持库失败!");
}
//启动Excell
if(!ExcelApp.CreateDispatch("Excel.Application",NULL))
{
AfxMessageBox("创建Excell服务失败!");
exit(1);
}
ExcelApp.SetVisible(FALSE);
//利用模板文件建立新文档
CString strPath;
CString strPath1;
GetCurrentDirectory(MAX_PATH,strPath.GetBuffer(MAX_PATH));//获取当前路径
strPath1.Format("%s//11.xls",strPath);//要操作的excel表的名字
wbsMybooks.AttachDispatch(ExcelApp.GetWorkbooks(),TRUE);
wbMyBook.AttachDispatch(wbsMybooks.Add(_variant_t(strPath1)));
wssMySheets.AttachDispatch(wbMyBook.GetWorksheets(),true);
wsMySheet.AttachDispatch(wssMySheets.GetItem(_variant_t("sheet1")),TRUE);
MyRange.AttachDispatch(wsMySheet.GetCells(),true);
int row = 2;
CString sMsg;
ExcelToString(row, 1, sMsg); //读取row行1列的数据至sMsg中
CDialog::OnOK();
}
void CExceltestDlg::ExcelToString(int row, int col, CString& sMsg)
{
VARIANT vMsg;
char cMsg[512];
vMsg = MyRange.GetItem(_variant_t((long)row),_variant_t((long)col));
_bstr_t bMsg = (_bstr_t)vMsg;
strcpy(cMsg,bMsg);
sMsg = cMsg;
}
昨天忘了说明一点,_variant_t类型需要包含下面这个头文件才能识别:
#include <comdef.h>