存储过程:将SQL Server表导到Excel中

任务】:
      将NorthWind数据库中的Products表中的全部数据导到E:\Media\JackieAillo.xls 中。
步骤】:
一、创建存储过程(p_export_to_excel):
1、判断p_export_to_excel存储过程是否已经存在,如果存在则将改存储过程删除,您可以在企业管理器中直接删除,也可以在查询分析其中执行下面的代码:
if exists (
select * from dbo.sysobjects
where id = object_id(N'[dbo].[p_export_to_excel]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1)

drop procedure [dbo].[p_export_to_excel]
go

2、新建名为p_export_to_excel的存储过程,创建代码如下:

create proc p_export_to_excel

@sqlstr sysname,
--查询语句,该查询语句的查询结果就是写到Excel中的数据。
--如果查询语句中使用了order by ,请加上top 100 percent, 

@path nvarchar(1000),
--导出路径,路径必须要用双斜杠,如"c:\\aillo\\tt\\"格式,而不能用"c:\aillo\t\"

@fname nvarchar(250), --文件名,需包括文件的扩展名,如:123.xls

@sheetname varchar(250)='' --要创建的工作表名,默认为文件名

as

declare @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='temp.xls'

if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')


--检查文件是否已经存在

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 5.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


--创建表的SQL

declare @tbname sysname

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

set @sql='select * into ['+@tbname+'] from('+@sqlstr+') a'

exec(@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 tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype

where b.name not in


('image','text','uniqueidentifier','sql_variant','ntext','varbinary','binary','timestamp')

and a.id=(select id from tempdb..sysobjects where name=@tbname)

select @sql='create table ['+@sheetname

+']('+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 5.0;HDR=YES

;DATABASE='+@path+@fname+''',['+@sheetname+'$])'


exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from ['+@tbname+']')


set @sql='drop table ['+@tbname+']'

exec(@sql)

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

二、在ASP.net程序代码(SQL_Export_To_Excel.aspx.cs)中调用存储过程:
      在设计界面中添加一个导出按钮,添加如下代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class SQL_To_Excel : System.Web.UI.Page
{
    public SqlConnection con()
    {
        string constr = "server=localhost;uid=sa;pwd=123456;database=NorthWind";
        SqlConnection mycon = new SqlConnection(constr);
        return mycon;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection connection = con();
        SqlCommand cmd = new SqlCommand("p_export_to_excel", connection);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1, p2, p3, p4;
        p1 = new SqlParameter("@sqlstr", "select * from Products");
        p2 = new SqlParameter("@path", "E:\\Media\\");
        p3 = new SqlParameter("@fname", "JackieAillo.xls");
        p4 = new SqlParameter("@sheetname", "AAA");
        cmd.Parameters.Add(p1);
        cmd.Parameters.Add(p2);
        cmd.Parameters.Add(p3);
        cmd.Parameters.Add(p4);
        try
        {
            connection.Open();
            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('数据已成功导到Excel中!')</script>");
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
        finally
        {
            connection.Close();
        }
    }
}

留言

Your email address will not be published. Required fields are marked *