您的位置:程序门 -> vb -> 基础类



vb程序如果将excel导入到sql数据问题!!!


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


vb程序如果将excel导入到sql数据问题!!!
发表于:2007-09-06 20:59:40 楼主
大家好,请问能不能用vb程序把excel导入到数据库里呢,因为我要解决的问题是:
各单位把本单位的人员管理情况每个月都要上报到总厂,在总厂把各个单位上报来的数据进行汇总,我用的是sql   2000   数据库,   郁闷中,有这方面经验的前辈请执教...
发表于:2007-09-06 22:00:041楼 得分:0
补充一下   没有联网   每个单位上传数据都是用的u盘
发表于:2007-09-06 22:07:192楼 得分:0
只要你的excel格式规范就可以
private   flag   as   boolean   '标记excel文件是否打开过
'打开excel文件
public   sub   openexcel(byval   strname   as   string)
if   flag   then
        closeexcel
end   if
set   xlsapp   =   createobject( "excel.application ")
set   xlsbook   =   xlsapp.workbooks.open(strname)
set   xlssheet   =   xlsbook.activesheet
flag   =   true
end   sub

'关闭excel文件
public   sub   closeexcel()
if   flag   then
        flag   =   false
        xlsbook.close
        xlsapp.quit
        set   xlsapp   =   nothing
        set   xlsbook   =   nothing
        set   xlssheet   =   nothing
end   if
end   sub

'取得excel文件的记录集
public   function   getexcelrs(byval   strname   as   string)   as   adodb.recordset
dim   rs   as   adodb.recordset
set   rs   =   new   adodb.recordset
dim   conn   as   string
rs.cursorlocation   =   aduseclient
rs.cursortype   =   adopendynamic
rs.locktype   =   adlockbatchoptimistic
conn   =   "data   provider=msdasql.1;driver=microsoft   excel   driver   (*.xls);dbq= "   &   strname
rs.open   "select   *   from   [sheet1$] ",   conn
set   getexcelrs   =   rs
set   rs   =   nothing
end   function

通过openexcel后检查选择的excel是否格式正确,可以看里面的字段名
比如第一个cell是:姓名
那么可以打开后这样检查,if   xlssheet.cell(1,1)= "姓名 "   then   bcheckfile=true
检查文件是可导入的以后
就可以关闭excel了closeexcel
然后就可以用getexcelrs来获取recordset
然后循环的读recordset,一条一条的insert到sql2000的固定表里面就ok了
发表于:2007-09-06 22:07:483楼 得分:0
如果你还不明白
我就没办法了
发表于:2007-09-11 09:52:584楼 得分:0
然后就可以用getexcelrs来获取recordset
然后循环的读recordset,一条一条的insert到sql2000的固定表里面就ok了
问题是循环到什么时候结束呢?
在不知道excel有多少条记录的情况下
??
发表于:2007-09-11 11:07:355楼 得分:0
可以用dts,保存个vb模块,改下代码就行
发表于:2007-09-11 11:47:016楼 得分:0
循环什么时候结束还问?
你不会用recordset吗?
recordset的内容就是excel的内容
这样的话,recordset.recordcount不就是记录数吗?
也就是循环的次数啊
发表于:2007-09-11 11:48:427楼 得分:0
先把recordset.movefirst
然后开始循环recordset.recordcount次
先判断是否recordset.eof
insert后,recordset.movenext
这样不就ok   了吗?

发表于:2007-09-11 14:51:008楼 得分:0
打开excel文件   然后把所需要保存的数据放到变量中(row(1,1)这个就是代表第一行,第一列单元格中的数据)   再把这些变量中的数据用sql插入语句插入到sql数据库里   就行了
发表于:2007-09-11 16:14:549楼 得分:0
楼上的
你这个方法太卡了
如果记录比较多的话
会运行n久
因为是循环读取excel

所以不如用recordset来的快
发表于:2007-09-11 16:35:2710楼 得分:0
数据量大时可用   sql   server   的   bulk   insert   语句,程序只要将符合格式的文件复制到指定目录然后执行   bulk   insert   就可以了。


快速检索

最新资讯
热门点击