KingAmu'Code

用SQL存储过程将数据导出到Excel

        string tmpTable = table_name.Text.ToString(); //收到下载的表名
        string tmpSavePath = Server.MapPath("../") + "DataChageFile\\"; //保存的路径
        string tmpExcel = "TmpExcel" + DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "") + ".xls"; //生成的临时EXCEL文件名
        string tmpSheet = "Tmp" + DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", ""); //生成临时的EXCEL表名

        if (tmpTable == "")
        {
            Response.Write("<script Language=javascript>alert('请输入表名!');history.back()</script>");
        }
        else
        {
            SqlConnection conn = mmsdb.conn(); conn.Open();
            string sql = "declare @sql varchar(8000)set @sql = 'select top 100 * from " + tmpTable + "'Exec H_SqlToExcel '" + tmpSavePath + "','" + tmpExcel + "','" + tmpSheet + "',@sql";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close(); conn = null;
        }

        Response.Redirect("..\\DataChageFile\\" + tmpExcel); //下载文件

 

 

 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[H_SqlToExcel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[H_SqlToExcel]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROC H_SqlToExcel
(
@Path varchar(100),--文件存放路径
@Fname varchar(100),--文件名字
@SheetName varchar(80),---工作表名字
@SqlStr varchar(8000)--查询语句,如果查询语句中使用了order by ,请加上top 100 percent,注意,如果导出表/视图,用上面的存储过程 
)
AS
SET NOCOUNT ON

declare @sql varchar(8000)
declare @obj int--OLE对象
declare @constr varchar(8000)
declare @err int
declare @out int
declare @fdlist varchar(8000)
declare @tbname sysname--临时表
declare @Src nvarchar(200)
declare @Desc nvarchar(200)

set @tbname='##tmp_'+convert(varchar(38),newid())

exec('select * into ['+@tbname +'] from '+'('+@sqlStr+') A')

select @fdlist = ''

set @sql= @path+@fname
set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
+';CREATE_DB="'+@sql+'";DBQ='+@sql

--生成Excel的列
set @sql = ''
select @sql = @sql+','+'['+a.name+'] '+ case when b.name like '%char' then case when a.length >255 then 'memo' else 'text('+cast(a.length as varchar)+')' end
when b.name like '%int' or b.name='bit' then 'int'
when b.name like '%datetime' then 'datetime'
when b.name like '%money' then 'money'
when b.name like '%text' then 'memo'
else b.name
end, 
@fdlist = @fdlist+','+'['+a.name+']' 
from tempdb..syscolumns a join tempdb..systypes b on a.xtype = b.xusertype 
where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp') 
and id in(select id from tempdb..sysobjects where name = @tbname) order by colorder
if @@rowcount=0 return

set @fdlist = substring(@fdlist,2,8000)

--连接数据库
exec @err=sp_oacreate 'adodb.connection',@obj out
if @err <> 0 goto lberror
exec @err=sp_oamethod @obj,'open',null,@constr
if @err <> 0 goto lberror
--创建工作薄
select @sql='create table ['+@sheetname
+']('+substring(@sql,2,8000)+')'

exec @err=sp_oamethod @obj,'execute',@out out,@sql--@sql为excute方法提供参数

if @err <> 0 goto lberror

exec @err=sp_oadestroy @obj

--导入数据
set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES
;DATABASE='+@path+@fname+''',['+@sheetname+'$])'
--print @sql
exec ('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from ['+@tbname+']')

exec('drop table ['+@tbname+']')
return


lberror:
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
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

posted on 2010-02-05 13:52  阿牧  阅读(1788)  评论(0编辑  收藏  举报

导航