资源描述:
《sqlserver与excel中数据的导入导出基本方法》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、从SQLServer中导入/导出Excel的基本方法从sqlserver中导入/导出excel的基本方法/*=========== 导入/导出excel的基本方法===========*/从excel文档中,导入数据到sql数据库中,很简单,直接用下面的语句:/*=============================================*/--假如接受数据导入的表已存在insertinto表select*fromopenrowset(microsoft.jet.oledb.4.0,e
2、xcel5.0;hdr=yes;database=c:test.xls,sheet1$)--假如导入数据并生成表select*into表fromopenrowset(microsoft.jet.oledb.4.0,excel5.0;hdr=yes;database=c:test.xls,sheet1$)/*===========================================*/--假如从sql数据库中,导出数据到excel,假如excel文档已存在,而且已按照要接收的数据创建好表头
3、,就能够简单的用:insertintoopenrowset(microsoft.jet.oledb.4.0,excel5.0;hdr=yes;database=c:test.xls,sheet1$)select*from表--假如excel文档不存在,也能够用bcp来导成类excel的文档,注意大小写:--导出表的情况execmaster..xp_cmdshellbcp数据库名.dbo.表名out"c:test.xls"/c-/s"服务器名"/u"用户名"-p"密码"--导出查询的情况execmas
4、ter..xp_cmdshellbcp"selectau_fname,au_lnamefrompubs..authorsorderbyau_lname"queryout"c:test.xls"/c-/s"服务器名"/u"用户名"-p"密码"/*--说明:c:test.xls 为导入/导出的excel文档名.sheet1$ 为excel文档的工作表名,一般要加上$才能正常使用.--*/--上面已说过,用bcp导出的是类excel文档,其实质为文本文档,--要导出真正的excel文档.就用下面的
5、方法/*--数据导出excel 导出表中的数据到excel,包含字段名,文档为真正的excel文档 ,假如文档不存在,将自动创建文档 ,假如表不存在,将自动创建表 基于通用性考虑,仅支持导出标准数据类型--邹建2003.10--*//*--调用示例 p_exporttb@tbname=地区资料,@path=c:,@fname=aa.xls--*/ifexists(select*fromdbo.sysobjectswhereid=object_id(n[dbo].[p_exporttb])andob
6、jectproperty(id,nisprocedure)=1)dropprocedure[dbo].[p_exporttb]gocreateprocp_exporttb@tbnamesysname, --要导出的表名@pathnvarchar(1000), --文档存放目录@fnamenvarchar(250)= --文档名,默认为表名asdeclare@errint,@srcnvarchar(255),@descnvarchar(255),@outintdeclare@objint,@co
7、nstrnvarchar(1000),@sqlvarchar(8000),@fdlistvarchar(8000)--参数检测ifisnull(@fname,)=set@fname=@tbname+.xls--检查文档是否已存在ifright(@path,1)<>set@path=@path+createtable#tb(abit,bbit,cbit)set@sql=@path+@fnameinsertinto#tbexecmaster..xp_fileexist@sql--数据库创建语句set@s
8、ql=@path+@fnameifexists(select1from#tbwherea=1) set@constr=driver={microsoftexceldriver(*.xls)};dsn=;readonly=false +;create_db=" +;database=+@sql+"--连接数据库exec@err=sp_oacreateadodb.connection,@objoutif@err<>0gotolberrexec@err=sp_