写工具软件,一直和excel打交道,之前一直采用excel.cpp.excel.h直接添加到工程的方式来读写excel,现在由于要对代码进行单元测试,excel。cpp和excel.h文件中竟然有上万行代码,会引起很大的测试量,因此打算采用dll调用的方式来读写excel。
1. 首先从本机安装的office软件中导出DLL文件。
在程序的的stdafx.h中增加以下内容。文件路径修改为本机安装office的路径
#import "C:\\Program Files (x86)\\Common Files\\microsoft shared\\OFFICE14\\MSO.DLL"\
rename("RGB","MsoRGB") \
rename("SearchPath","MsoSearchPath")
#import "C:\\Program Files (x86)\\Common Files\\microsoft shared\\VBA\\VBA6\\VBE6EXT.OLB"
#import "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE"\
rename("DialogBox","ExcelDialogBox") \
rename("RGB","ExcelRGB") \
rename("CopyFile","ExcelCopyFile") \
rename("ReplaceText","ExcelReplaceText") \
exclude("IFont","IPicture") no_dual_interfaces
然后运行一下软件,就可以得到EXCEL.tlh,EXCEL.tli,MSO.tlh,MSO.tli,VBE6EXT.tlh,VBE6EXT.tli等文件了。
2.读取EXCEL
先在要操作excel的文件的头部添加using namespace Excel;表明要使用excel的类库
bool readExcel(CString strFileName)
{
CoInitialize(NULL); //初始化
Excel::_ApplicationPtr ExcelApp;
Excel::_WorkbookPtr Excelbook;
Excel::WorksheetsPtr Excelsheets;
Excel::_WorksheetPtr sheet;
HRESULT hr = ExcelApp.CreateInstance(L"Excel.Application");
ASSERT(SUCCEEDED(hr));
ExcelApp->Visible = false; //使Excel不可见
ExcelApp->UserControl = true; //允许其它用户控制Excel
ExcelApp->DisplayAlerts = false; //不弹出提示
Excelbook = ExcelApp->Workbooks->Open(LPCTSTR(strFileName));
Excelsheets = Excelbook->Worksheets;
int shtCount = Excelsheets->Count;
//////////////////////////////////////////////////////////////////////////
for (short k = 1; k <= shtCount; k++)
{
sheet = Excelsheets->Item[k];
if (sheet != NULL)
{
CString sheetName = LPCTSTR(sheet->GetName());
Excel::RangePtr rgMyRge;
rgMyRge= sheet->Cells;
Excel::RangePtr usedRange,cell;
usedRange = sheet->UsedRange;
rgMyRge = usedRange->Rows;
long iRowNum = rgMyRge->Count;
rgMyRge = usedRange->Columns;
long iColNum = rgMyRge->Count;
rgMyRge = sheet->GetRange(_bstr_t(_T("A1")));
for(int m = 2;m<iRowNum;m++)
{
for(int j = 1; j<iColNum; j++)
{
cell = rgMyRge->GetItem(_variant_t( (long)(m)), _variant_t( (long)j)).pdispVal;
CString strItemName = cell->GetText().bstrVal;//strItemName就是读取到的内容
}
}
}
}
Excelbook->Close(VARIANT_TRUE);
ExcelApp->Quit();
return true;
}