#include "excel.h"
#include <comdef.h>
void ExcelToString(int row, int col, CString& sMsg);
_Application ExcelApp; //Excell 表格操作所需要的变量
Workbooks wbsMybooks;
_Workbook wbMyBook;
Worksheets wssMySheets;
_Worksheet wsMySheet;
Range MyRange;
void CYcDlg::OnButton1()
{
// TODO: Add your control notification handler code here
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("C:\\Documents and Settings\\Administrator\\桌面\\test\\test\\1.xls")));
wssMySheets.AttachDispatch(wbMyBook.GetWorksheets(),true);
wsMySheet.AttachDispatch(wssMySheets.GetItem(_variant_t("sheet1")),TRUE);
MyRange.AttachDispatch(wsMySheet.GetCells(),true);
int row = 1;
CString sMsg;
ExcelToString(row, 1, sMsg); //读取row行1列的数据至sMsg中
MessageBox(sMsg);
}
void CYcDlg::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;
}