sqlserver 导出数据到Excel
1、导出非正式Excel
EXEC master..xp_cmdshell \'bcp t.dbo.tcad out D:\MySelf\output\Temp.xls -c -q -S"." -U"sa" -P"sql2008"\'
--参数:S 是SQL服务器名;U是用户;P是密码
2、启用/停用xp_cmdshell
-- To allow advanced options to be changed.
EXEC sp_configure \'show advanced options\', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure \'xp_cmdshell\', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
-- To Disable advanced options to be changed.
EXEC sp_configure \'show advanced options\', 0
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
EXEC sp_configure \'xp_cmdshell\', 0
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
3、启用/停用Ad Hoc Distributed Queries
--启用Ad Hoc Distributed Queries的方法,执行下面的查询语句就可以了:
exec sp_configure \'show advanced options\',1
reconfigure
exec sp_configure \'Ad Hoc Distributed Queries\',1
reconfigure
--使用完毕后,一定要关闭它,因为这是一个安全隐患,执行下面的SQL语句用来关闭:
exec sp_configure \'Ad Hoc Distributed Queries\',0
reconfigure
exec sp_configure \'show advanced options\',0
reconfigure
4、传说中的导出正式的Excel(实验不成功)
/*--数据导出EXCEL
导出表中的数据到Excel,包含字段名,文件为真正的Excel文件
,如果文件不存在,将自动创建文件
,如果表不存在,将自动创建表
基于通用性考虑,仅支持导出标准数据类型
--邹建 2003.10(引用请保留此信息)--*/
/*--调用示例
p_exporttb @tbname=\'地区资料\',@path=\'c:\\',@fname=\'aa.xls\'
--*/
--create proc p_exporttb
declare
@tbname varchar(100), --要导出的表名
@path nvarchar(1000), --文件存放目录
@fname nvarchar(250), --文件名,默认为表名
@err int,
@src nvarchar(255),
@desc nvarchar(255),
@out int,
@obj int,
@constr nvarchar(1000),
@sql varchar(8000),
@fdlist varchar(8000)
set @tbname=\'tcad\'
set @path=\'D:\MySelf\output\\'
set @fname=\'test\'
--参数检测
if isnull(@fname,\'\')=\'\'
set @fname=@tbname+\'.xls\'
--检查文件是否已经存在
if right(@path,1)<>\'\\'
set @path=@path+\'\\'
--create table #tb(a bit,b bit,c bit)
set @sql=@path+@fname
--insert into #tb exec master..xp_fileexist @sql
--数据库创建语句
set @sql=@path+@fname
--if exists(select 1 from #tb where a=1)
set @constr=\'DRIVER={Microsoft Excel Driver (*.xls)};DSN=\'\'\'\';READONLY=FALSE\'
+\';CREATE_DB="\'+@sql+\'";DBQ=\'+@sql
--else
--set @constr=\'Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES\'
--+\';DATABASE=\'+@sql+\'"\'
exec @constr
继续努力!!!