/*--呼叫示例
p_exporttb @sqlstr='select * from 地區資料'
,@path='c:/',@fname='aa.xls',@sheetname='地區資料'
--*/
create proc p_exporttb
@tbname sysname, --要匯出的表名
@path nvarchar(1000), --檔案存放目錄
@fname nvarchar(250)='' --檔名,預設為表名
asdeclare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)
--引數檢測
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=;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 @err=sp_oacreate 'adodb.connection',@obj out
if @err<>0 goto lberr
exec @err=sp_oamethod @obj,'open',null,@constr
if @err<>0 goto lberr
/*--如果覆蓋已經存在的表,就加上下面的語句
--建立之前先刪除表/如果存在的話
select @sql='drop table ['+@tbname+']'
exec @err=sp_oamethod @obj,'execute',@out out,@sql
--*/
--建立表的sql
select @sql='',@fdlist=''
select @fdlist=@fdlist+',['+a.name+']'
,@sql=@sql+',['+a.name+'] '
+case when b.name in('char','nchar','varchar','nvarchar') then
'text('+cast(case when a.length>255 then 255 else a.length end as varchar)+')'
when b.name in('tynyint','int','bigint','tinyint') then 'int'
when b.name in('smalldatetime','datetime') then 'datetime'
when b.name in('money','smallmoney') then 'money'
else b.name end
from syscolumns a left join systypes b on a.xtype=b.xusertype
where b.name not in('image','text','uniqueidentifier','sql_variant','ntext','varbinary','binary','timestamp')
and object_id(@tbname)=id
select @sql='create table ['+@tbname
+']('+substring(@sql,2,8000)+')'
,@fdlist=substring(@fdlist,2,8000)
exec @err=sp_oamethod @obj,'execute',@out out,@sql
if @err<>0 goto lberr
exec @err=sp_oadestroy @obj
--匯入資料
set @sql='openrowset(''microsoft.jet.oledb.4.0'',''excel 8.0;hdr=yes
;database='+@path+@fname+''',['+@tbname+'$])'
exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from '+@tbname)
return
lberr:
exec sp_oageterrorinfo 0,@src out,@desc out
lbexit:
select cast(@err as varbinary(4)) as 錯誤號
,@src as 錯誤源,@desc as 錯誤描述
select @sql,@constr,@fdlist
go****************************************
ningoo注:
excel檔案每個工作表不能超過65536條記錄
解決辦法:
.如果資料量大於65536,可以在呼叫儲存過程前先將要匯出的table拆分成幾個小的臨時table,然後
在分別匯出到不同的工作表中
將資料匯出到excel
using system using system.data.oledb using system.io using system.windows.forms namespace postgraduateclient public sqltoexcel string tablename public...
將資料匯出到excel
前台jsp呼叫 function outexe action 將資料匯出到excel action value lpm grpinfoexl public string lpmexl throws exception else if g.getregtime null else rows 當stri...
將mysql資料匯出到excel表中
title 資料備份 date y m d h i s sep t crlf n conn mysql connect localhost root or die 不能連線資料庫 mysql select db 資料庫名稱 conn mysql query set names utf8 header...