c++ 读写Excel及数据导入SQLServer
     
          C++操作Excel ,网上的资料还是比较多的,写这篇文章也是分享给初学者一些经验。

本人 觉得CSpreadSheet.h这个类封装的还不错。下面我就如何使用这个类介绍一下,

////////////////main.cpp/////////////////////////////////////////////////////

#include <string>
#include<afxdb.h>
#include<odbcinst.h>
#include "CSpreadSheet.h"
using std::string; #pragma warning(disable:4146)
#pragma warning(disable:4786)
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF") //插入到数据库
bool InsertExcel(CString str1,CString str2)
{
try
{
CDatabase m_db;
if (!m_db.IsOpen())
{
m_db.OpenEx("Dsn=MyDatabase;uid=Administrator;trusted_connection=Yes;app=Microsoft? Visual Studio? 2005;wsid=LIYU\SQLEXPRESS;database=MyDdatabase",0);
} CString sql("insert into Students(myname,age) values('"+ str1+"','"+str2+"')");
m_db.ExecuteSQL(sql); if(m_db.IsOpen())
{
m_db.Close();
}
return true;
}
catch(_com_error e)
{
string ErrorMessage("数据库连接关闭失败:"),Description,Source;
Description=e.Description();
Source=e.Source();
ErrorMessage+=e.ErrorMessage();
ErrorMessage=ErrorMessage+"\r\n"+Source+"\r\n"+Description;
::MessageBox(NULL,ErrorMessage.c_str(),"错误",MB_OK);
return false;
} }
//获取路径
CString GetAddr()
{ 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";
return sFile;
}
//得到驱动
CString 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;
}
//读取Excel
void ReadFromExcel()
{
TRY
{
CString str=GetAddr();
if(str.IsEmpty())
::MessageBox(NULL,"无法获取当前路径",NULL,MB_OK);
else
{
CSpreadSheet SS(str,"Students");
CStringArray Rows, Column;
CString strContents = "";
CString sItem[3]={"0"};
for (int i = 2; i < SS.GetTotalRows()+1; i++)
{
// 读取一行
SS.ReadRow(Rows, i);
strContents.Empty();
for (int j = 0; j < Rows.GetSize(); j++)
{
strContents = Rows.GetAt(j);
sItem[j]=strContents;
printf("%s\t",sItem[j]);
}
printf("\n");
if(!InsertExcel(sItem[1],sItem[2]))
{
::MessageBox(NULL,"导入数据出错","错误",MB_OK);
return;
}
}
}
}
CATCH(CDBException, e)
{
// 数据库操作产生异常时...
AfxMessageBox("数据库错误: " + e->m_strError);
}
END_CATCH;
} //写Excel
void WriteFromExcel(int num,CString str1,CString str2,CString str3)
{
CString path=GetAddr();
if(path.IsEmpty())
::MessageBox(NULL,"获取路径错误",NULL,MB_OK);
else
{
// 新建Excel文件名及路径,TestSheet为内部表名
CSpreadSheet SS(path,"StudentsOut");
CStringArray sampleArray, testRow;
SS.BeginTransaction(); // 加入标题
sampleArray.RemoveAll();
sampleArray.Add("ID");
sampleArray.Add("myname");
sampleArray.Add("age"); SS.AddHeaders(sampleArray);
testRow.Add(str1);
testRow.Add(str2);
testRow.Add(str3);
SS.AddRow(testRow,num,true);
SS.Commit();
}
} //查询
bool selectExcel()
{
_ConnectionPtr m_pConnection; //connection object's pointer
_CommandPtr m_pCommand; //command object's pointer
_ParameterPtr m_pParameter; //Parameter object's pointer
_RecordsetPtr m_pRecordset; HRESULT hr;
try
{
// 创建连接对象
hr=m_pConnection.CreateInstance(__uuidof(Connection));
m_pRecordset.CreateInstance(__uuidof(Recordset));
if(!SUCCEEDED(hr)) return FALSE; // 连接数据库
m_pConnection->ConnectionString="File Name=LinkDatabase.udl";
m_pConnection->ConnectionTimeout=20;//等待连接的时间为20s
hr=m_pConnection->Open("","","",adModeUnknown);
if(!SUCCEEDED(hr)) return FALSE; // 查询数据库
_variant_t RecordsAffected;
std::string sql= "select * from Students";
char * str=(char*)sql.c_str(); m_pRecordset=m_pConnection->Execute(str,&RecordsAffected,adCmdText);
//m_pRecordset-> Open(str, _variant_t((IDispatch *)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
int i=2;
// 遍历查询结果
while (!m_pRecordset->adoEOF)
{
printf("%s\t",(char*)(_bstr_t)m_pRecordset->GetCollect("ID"));
printf("%s\t",(char*)(_bstr_t)m_pRecordset->GetCollect("myname"));
printf("%s\n",(char*)(_bstr_t)m_pRecordset->GetCollect("age"));
CString str1=(CString)m_pRecordset->GetCollect("ID");
CString str2=(CString)m_pRecordset->GetCollect("myname");
CString str3=(CString)m_pRecordset->GetCollect("age"); WriteFromExcel(i++,str1,str2,str3);
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
// 关闭数据库连接
if(m_pConnection!=NULL)
{
m_pConnection->Close();
m_pConnection = NULL ; }
}
catch(_com_error e)
{
string ErrorMessage("数据库连接关闭失败:"),Description,Source;
Description=e.Description();
Source=e.Source();
ErrorMessage+=e.ErrorMessage();
ErrorMessage=ErrorMessage+"\r\n"+Source+"\r\n"+Description;
::MessageBox(NULL,ErrorMessage.c_str(),"错误",MB_OK);
return FALSE;
}
} int main()
{
CoInitialize(NULL);
// ReadFromExcel();//读取Excel到数据库
selectExcel();
CoUninitialize( );
system("pause");
return 0;
}
////////////////mian.cpp////////////////////////////////////////////////

c++ 读写Excel及数据导入SQLServer的更多相关文章

  1. 将Excel中数据导入数据库(二)

    在上篇文章中介绍到将Excel中数据导入到数据库中,但上篇文章例子只出现了nvachar类型,且数据量很小.今天碰到将Excel中数据导入数据库中的Excel有6419行,其中每行均有48个字段,有i ...

  2. Excel表数据导入Sql Server数据库中

    Excel表数据导入Sql Server数据库的方法很多,这里只是介绍了其中一种: 1.首先,我们要先在test数据库中新建一个my_test表,该表具有三个字段tid int类型, tname nv ...

  3. Excel的数据导入到PB的DW中

    Excel的数据导入到PB的DW中//==================================================================== // Event:cb_ ...

  4. Visual Basic 2012 借助DataGridView控件将Excel 2010数据导入到SQL server 2012

    (注:注释的颜色原本为绿色,在这里变为黑色,有点不便,但不会造成阅读影响.放入Visual Basic2012代码编辑器后会还原成绿色.) 摘  要:DataGridView控件作为数据传输的中介,只 ...

  5. 将Excel中数据导入数据库(三)

    上篇文章将Excel中数据导入数据库时,将从Excel读入的数据均转换成了数据库相应字段的类型,其实这是没有必要的,因为对于数据库各种类型的插入,均可以字符串格式插入.比如表WQ_SWMSAR_A字段 ...

  6. 将Excel中数据导入数据库(一)

    在工作中经常要将Excel中数据导入数据库,这里介绍一种方法. 假如Excel中的数据如下: 数据库建表如下: 其中Id为自增字段: Excel中数据导入数据库帮助类如下: using System; ...

  7. SQL SERVER 与ACCESS、EXCEL的数据导入导出转换

    * 说明:复制表(只复制结构,源表名:a 新表名:b)      select * into b from a where 1<>1 * 说明:拷贝表(拷贝数据,源表名:a 目标表名:b) ...

  8. Excel表数据导入数据库表中

    ***Excel表数据导入到数据库表中 通过数据库表的模板做成‘Excel’表的数据导入到数据库相应的表中(注意:主表 和 从表的关系,要先导‘主表’在导入从表) 过程:通过数据库的导入工具—先导入为 ...

  9. 把Excel的数据导入到数据库

    将Excel作为数据源,将数据导入数据库,是SSIS的一个简单的应用,下图是示例Excel,数据列是code和name 第一部分,Excel中的数据类型是数值类型 1,使用SSDT创建一个packag ...

随机推荐

  1. poj2253 Frogger(Floyd)

    题目链接 http://poj.org/problem?id=2253 题意 给出青蛙A,B和若干石头的坐标,现在青蛙A要跳到青蛙B所在的石头上,求出所有路径中最远那一跳的最小值. 思路 Floyd算 ...

  2. 一个简单的ajax上传 上传进度显示

    本例用了jquery.form.js请到演示页面查看 CSS Code <style> form { display: block; margin: 20px auto; backgrou ...

  3. 转:perl源码审计

    转:http://www.cgisecurity.com/lib/sips.html Security Issues in Perl Scripts By Jordan Dimov (jdimov@c ...

  4. javascript 原生得到document.Element的方法

    今天这里写这个博客的主要目的是记录一下javascript原生的选择dom的集中方法. 1.document.getElementById.这个方法接收1个参数,就是DOM元素的id(区分大小写),这 ...

  5. `__pycache__` 是什么

    为了提高模块加载的速度,每个模块都会在 __pycache__ 文件夹中放置该模块的预编译模块,命名为 module.version.pyc, version 是模块的预编译版本编码,一般都包含 Py ...

  6. Vue 2.0学习(五)v-bind及class与style绑定

    DOM元素经常会动态地绑定一些class类名或style样式. 基本用法 <div id="app"> <a v-bind:href="url" ...

  7. JMS介绍:我对JMS的理解和认识

    [ZT]JMS介绍:我对JMS的理解和认识 转自:http://blog.csdn.net/KimmKing/archive/2011/06/30/6577021.aspx,感谢作者KimmKing ...

  8. Linux下C语言多文件的编译以及makefile的应用

    1.关于编译和链接 一般来说,无论是C.C++,首先要把源文件编译成中间代码文件,在Windows下也就是.obj文件,UNIX下是.o文件,即Object File,这个动作叫做编译(compile ...

  9. luoguP3317 [SDOI2014]重建 变元矩阵树定理 + 概率

    首先,我们需要求的是 $$\sum\limits_{Tree} \prod\limits_{E \in Tree} E(u, v) \prod\limits_{E \notin Tree} (1 - ...

  10. 使用百度ai接口加图灵机器人完成简单web版语音对话

    app文件 from flask import Flask, request, render_template, jsonify, send_file from uuid import uuid4 i ...