步骤及说明: if (!AfxOleInit()) { AfxMessageBox("初始化OLE DLL失败:("); return FALSE; } 3. //创建Connection对象并连接数据库 _Connection m_pConnection; BOOL CGradeCounterDlg::ConnectionDb() { //创建ADO连接 m_pConnection.CreateInstance(__uuidof(Connection)); CString strSQL; strSQL.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s; Extended Properties = Excel 5.0;Persist Security Info=False",m_fn); //m_fn表示输入的excel文件路径名 说明: (1)通过Microsoft Jet 数据库引擎实现对Excel表的连接; (2)不同版本的Excel对应不同的属性值:用于 Extended Properties 值设置有效 Excel 版本。 对于 Microsoft Excel 8.0 (97)、9.0 (2000) 和 10.0 (2002) 工作簿,使用 Excel 8.0; (3)Excel 工作簿的区域中第一行默认认为可标题行 (或字段名)。如果第一个区域不包含标题, 可指定 HDR = NO 您连接字符串中扩展属性中。 如果首行不包含页眉, OLEDB 提供程序自动名称字段对 (其中将 F 1 表示第一个字段, F2 将表示第二个字段等)) try{ //打开****.xls m_pConnection->Open((_bstr_t)strSQL,"","",adModeUnknown); } catch (_com_error e) { CString strError; strError.Format("警告:打开链接发生异常。错误信息:%s",e.ErrorMessage()); AfxMessageBox(strError); return false; } return true; } 4. 创建记录集对象 _RecordsetPtr m_pRecordset; CString strSQL=_T(""); strSQL.Format(_T("SELECT * FROM [Sheet1$] "));//excel表名称需写成[xxx$]形式,否则编译时出现IDispatch error #3127错误 m_pRecordset.CreateInstance(__uuidof(Recordset)); try{ m_pRecordset->Open((_bstr_t)strSQL.AllocSysString(), (_variant_t)m_pConnection.GetInterfacePtr(),// 获取库接库的IDispatch指针 adOpenDynamic, adLockOptimistic, adCmdText); } catch (_com_error e) { CString strError; strError.Format("警告:打开数据表时发生异常。错误信息: %s",e.ErrorMessage()); AfxMessageBox(strError); return ; } 5. 成绩计算统计 获取表格数据时可以使用m_pRecordset->GetFields()->GetItem((long)i)->Value;A列为第0列,B列为第1列,使用另一种函数m_pRecordset -> GetCollect(L"字段名")编译错误,原因可能是字符段名为汉字,表格单元格式为数值或常规时,数据类型默认为VT_R8,即_variant_t.vt = VT_R8,表示数据为double型数据。 写入计算结果到excel表格可以使用m_pRecordset -> GetFields() -> GetItem((long)i) -> Value = _variant_t(result),result表示计算结果。 6. 程序说明: 本程序基于ADO组件动态访问excel表格,计算学生成绩总分,公式为D+E+H*0.7,统计最高分,最低分,平均分,统计优秀,良好,中等,及格,不及格学生人数及所占比例。
|
Ado操作excel表格实现成绩计算及统计
最新推荐文章于 2023-03-25 21:36:14 发布