VC读写EXCEL文件类(已安装excel)- VC学习之路- CSDN博客 下载本文

VC读写EXCEL文件类(已安装excel) - VC学习之路 -

CSDN博客

以下是.h文件 #pragma once class CReadWriteExcel { private:

long CStringToLong(CString sStr);

int GetColumnWidth(CString sA,CString sB);

BOOL CheckString(CString str,CString &sLeft,CString &sRight,long &nRight);

HRESULT AutoWrap(int autoType, VARIANT *pvResult, IDispatch *pDisp, LPOLESTR ptName, int cArgs...); public:

int ReadExcelStringArray(const CString

strfilename,CStringArray &strArray,const CString sBeginCell,const CString sEndCell);

BOOL WriteExcelStringArray(const CString strfilename,CStringArray &strArray,long nColumn); //BOOL SetRangValueType(int nType,const CString

sBeginCell,const CString sEndCell); };

//以下是.cpp文件 #include \

#include \

//读取数据,返回列数

int CReadWriteExcel::ReadExcelStringArray(const CString strfilename,CStringArray &strArray,CString sBeginCell,CString sEndCell) {

//检查Range输入,并计算行列

if(sBeginCell.IsEmpty()|| sEndCell.IsEmpty()) return -1; //转成大写

sBeginCell.MakeUpper(); sEndCell.MakeUpper();

CString sBL,sBR; long nB;

if(!CheckString(sBeginCell,sBL,sBR,nB)) return -1;

CString sEL,sER; long nE;

if(!CheckString(sEndCell,sEL,sER,nE)) return -1;

int col=GetColumnWidth(sBL,sEL); int row=nE-nB+1; strArray.RemoveAll(); strArray.SetSize(row*col);

//处理所有Excel数据,并把所有数据加入到一个二维数组中

CoInitialize(NULL); int i,j; //用来循环 // 获得EXCEL的CLSID CLSID clsid;

HRESULT hr = CLSIDFromProgID(L\&clsid); if(FAILED(hr)) {

AfxMessageBox(_T(\函数调用失败!\ return -1; }

// 创建实例 IDispatch *pXlApp;

hr = CoCreateInstance(clsid, NULL,

CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&pXlApp); if(FAILED(hr)) {

AfxMessageBox(_T(\请检查是否已经安装EXCEL!\ return -1; }

// 显示,将Application.Visible属性置1 VARIANT x; x.vt = VT_I4; x.lVal = 1;

AutoWrap(DISPATCH_PROPERTYPUT, NULL, pXlApp, L\

// 获取Workbooks集合 IDispatch *pXlBooks; {

VARIANT result; VariantInit(&result);

AutoWrap(DISPATCH_PROPERTYGET,