[转]MFC实现excel的读写操作


这个是使用ODBC来完成的

第一步:建立基于对话框的MFC工程,命名为MfctoExc;

第二步:添加两个头文件到stdafx.h,

         #include <afxdb.h>

           #include <odbcinst.h>

第三步:添加两个按钮控件和一个List Box控件,给List Box添加控制变量CListBox m_ExcelList;添加DDX_Control(pDX, IDC_LIST_BOX, m_ExcelList);

第四步:给两个按钮添加两个功能函数,读写excel

void CMfctoExcDlg::OnRead() 
{
// TODO: Add your control notification handler code here
CDatabase database;
    CString sSql;
    CString sItem1, sItem2,sItem3;
    CString sDriver;
    CString sDsn;
    CString sFile,sPath;

                                    
//获取主程序所在路径,存在sPath中
GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer ();
    int nPos;
nPos=sPath.ReverseFind ('\\');
sPath=sPath.Left (nPos);

sFile = sPath + "\\Demo.xls";     // 将被读取的Excel文件名

    // 检索是否安装有Excel驱动 "Microsoft Excel Driver (*.xls)" 
    sDriver = GetExcelDriver();
    if (sDriver.IsEmpty())
    {
        // 没有发现Excel驱动
        AfxMessageBox("没有安装Excel驱动!");
        return;
    }
   
    // 创建进行存取的字符串
    sDsn.Format("ODBC;DRIVER={%s};DSN=' ';DBQ=%s", sDriver, sFile);

    TRY
    {
        // 打开数据库(既Excel文件)
        database.Open(NULL, false, false, sDsn);
        
        CRecordset recset(&database);

        // 设置读取的查询语句.
        sSql = "SELECT Num,Name, Age " //设置索引顺序     
               "FROM Exceldemo " ;               
               "ORDER BY Name ";
   
        // 执行查询语句
        recset.Open(CRecordset::forwardOnly, sSql, CRecordset::readOnly);

        // 获取查询结果
        while (!recset.IsEOF())
        {
            //读取Excel内部数值
    recset.GetFieldValue("Num", sItem1);
            recset.GetFieldValue("Name", sItem2);
            recset.GetFieldValue("Age", sItem3);

    //显示记取的内容
    m_ExcelList.AddString( sItem1 + " --> "+sItem2+ " --> "+sItem3 );

            // 移到下一行
            recset.MoveNext();
        }

        // 关闭数据库
        database.Close();
                             
    }
    CATCH(CDBException, e)
    {
        // 数据库操作产生异常时...
        AfxMessageBox("数据库错误: " + e->m_strError);
    }
    END_CATCH;
}

void CMfctoExcDlg::OnWrite() 
{
// TODO: Add your control notification handler code here
CDatabase database;
CString sDriver = "MICROSOFT EXCEL DRIVER (*.XLS)"; // Excel安装驱动
CString sExcelFile,sPath;
CString sSql;
   
//获取主程序所在路径,存在sPath中
GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer ();
int nPos;
nPos=sPath.ReverseFind ('\\');
sPath=sPath.Left (nPos);

sExcelFile = sPath + "\\Demo.xls";     // 要建立的Excel文件

TRY
{
    // 创建进行存取的字符串
    sSql.Format("DRIVER={%s};DSN='';FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=\"%s\";DBQ=%s",sDriver, sExcelFile, sExcelFile);

    // 创建数据库 (既Excel表格文件)
    if( database.OpenEx(sSql,CDatabase::noOdbcDialog) )
    {
      // 创建表结构(序号、姓名、年龄)
      sSql = "CREATE TABLE Exceldemo (Num Number,Name TEXT,Age NUMBER)";//可以用中文表示序号,姓名,年龄等
      database.ExecuteSQL(sSql);

      // 插入数值
      sSql = "INSERT INTO Exceldemo (Num,Name,Age) VALUES (1,'小西',24)";
      database.ExecuteSQL(sSql);

      sSql = "INSERT INTO Exceldemo (Num,Name,Age) VALUES (2,'小东',22)";
      database.ExecuteSQL(sSql);

      sSql = "INSERT INTO Exceldemo (Num,Name,Age) VALUES (3,'小朱',25)";
      database.ExecuteSQL(sSql);

      sSql = "INSERT INTO Exceldemo (Num,Name,Age) VALUES (4,'小鸭',27)";
      database.ExecuteSQL(sSql);
    }     

    // 关闭数据库
    database.Close();

AfxMessageBox("Excel文件写入成功!");
}
CATCH_ALL(e)
{
    TRACE1("Excel驱动没有安装: %s",sDriver);
}
END_CATCH_ALL;
}
第五步:添加成员函数

CString CMfctoExcDlg::GetExcelDriver()
{
    char szBuf[2001];
    WORD cbBufMax = 2000;
    WORD cbBufOut;
    char *pszBuf = szBuf;
    CString sDriver;

    // 获取已安装驱动的名称(涵数在odbcinst.h里)
    if (!SQLGetInstalledDrivers(szBuf, cbBufMax, &cbBufOut))
        return "";
    
    // 检索已安装的驱动是否有Excel...
    do
    {
        if (strstr(pszBuf, "Excel") != 0)
        {
            //发现 !
            sDriver = CString(pszBuf);
            break;
        }
        pszBuf = strchr(pszBuf, '\0') + 1;
    }
    while (pszBuf[1] != '\0');

    return sDriver;

}

文件存储路径设置:

CString filename, sExcelFile ;
CFileDialog fileDlg (FALSE, "Path", filename,OFN_FILEMUSTEXIST| OFN_HIDEREADONLY, "*.xls");
if( fileDlg.DoModal()==IDOK)
    {
    sExcelFile = fileDlg.GetPathName();    // 要建立的Excel文件
        CFileFind finder;
        BOOL bWorking = finder.FindFile(sExcelFile);//寻找文件

if (bWorking)//如果已经存在文件,则删除
        {
            CFile::Remove((LPCTSTR)sExcelFile);
        }
}
else
   return ;

将变量写入Excel可以用下面的笨方法:

for(int i=0;i<5;i++)
   {
    sSql = "INSERT INTO Exceldemo (Num,Name,Age) VALUES (";
    str0.Format("%d",a[i]);
    sSql=sSql+str0;
    sSql=sSql+",'";
    sSql=sSql+str[i];
    sSql=sSql+"',";
    str0.Format("%0.7f",data[i]);
    sSql=sSql+str0;
    sSql=sSql+")";
      database.ExecuteSQL(sSql);
   }     

其中a[ ]是一个int型数组,str[ ]是CString数组,data[ ]是float数字

你可能感兴趣的:(C++,Excel,Microsoft,word,mfc)