我们的上位机需要一个配置文件INI,但是数据项有点多看起来很乱,而EXCEL在保存一些配置数据的时候有独特的优势,所以就在EXCEL里边配置,利用上位机读EXCEL。
一、建立工程:
a. project->add class->MFC class from typelib (项目->添加类->Typelib中的MFC类)导入Excel.exe,一般都在C:/Program Files/Microsoft Office/Office12路径下(即选择你的office安装路径下的excel.exe加入)
b. 选中以下几项_Application,_WorkSheet,_WorkBook,WorkSheets,WorkBooks,Range,然后导入;
c. 导入后自动在工程中添加CApplication,CWorkSheet,CWorkBook,CWorkSheets,CWorkBooks,CRange这些类;
然后需要把这些类的头文件中的第一句话 #import ".......EXCEL.EXE" nonamespace 删除;
引入之后如果编译遇到错误,Not enough actual parameters for macro 'DialogBoxW'. 让人头疼!
解决方法是在CRange类中,VARIANT DialogBox()前面添加下划线变成VARIANT _DialogBox(),解决了!
二、添加头文件
#include "CApplication.h"
#include "CRange.h"
#include "CWorkbook.h"
#include "CWorkbooks.h"
#include "CWorksheet.h"
#include "CWorksheets.h"
三、添加操作代码
void CMonitorDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CApplication app;
CWorkbooks books;
CWorkbook book;
CWorksheets sheets;
CWorksheet sheet;
CRange range;
CRange iCell;
LPDISPATCH lpDisp;
COleVariant vResult;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if(!app.CreateDispatch("Excel.Application"))
{
AfxMessageBox("无法启动Excel服务器!");
return;
}
app.put_Visible(TRUE);
app.put_UserControl(FALSE);
books.AttachDispatch(app.get_Workbooks());
lpDisp = books.Open("D:\\test.xls",covOptional, covOptional, covOptional, covOptional, covOptional,covOptional, covOptional, covOptional, covOptional, covOptional,covOptional, covOptional, covOptional,covOptional);
//得到Workbook
book.AttachDispatch(lpDisp);
//得到Worksheets
sheets.AttachDispatch(book.get_Worksheets());
//得到当前活跃sheet
//如果有单元格正处于编辑状态中,此操作不能返回,会一直等待
lpDisp=book.get_ActiveSheet();
sheet.AttachDispatch(lpDisp);
//读取第一个单元格的值
range.AttachDispatch(sheet.get_Cells());
range.AttachDispatch(range.get_Item (COleVariant((long)2),COleVariant((long)2)).pdispVal);
/*COleVariant*/ vResult =range.get_Value2();
CString str;
if(vResult.vt == VT_BSTR) //字符串
{
str=vResult.bstrVal;
}
else if (vResult.vt==VT_R8) //8字节的数字
{
str.Format("%f",vResult.dblVal);
}
MessageBox(str);
books.Close();
app.Quit(); // 退出
range.ReleaseDispatch();
sheet.ReleaseDispatch();
sheets.ReleaseDispatch();
book.ReleaseDispatch();
books.ReleaseDispatch();
app.ReleaseDispatch();
//OnOK();
}
有读取单元格的函数基本也就差不多了,有想法就去做