1 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_exporttb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)2 drop procedure [dbo].[p_exporttb]3 GO4
5 /*--数据导出EXCEL6
7 导出表中的数据到Excel,包含字段名,文件为真正的Excel文件8 ,如果文件不存在,将自动创建文件9 ,如果表不存在,将自动创建表10 基于通用性考虑,仅支持导出标准数据类型11
12 --邹建 2003.10(引用请保留此信息)--*/
13
14 /*--调用示例15
16 p_exporttb @tbname='地区资料',@path='c:',@fname='aa.xls'17 --*/
18 create proc p_exporttb19 @tbname sysname, --要导出的表名20 @path nvarchar(1000), --文件存放目录21 @fname nvarchar(250)='' --文件名,默认为表名22 as
23 declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
24 declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)25
26 --参数检测27 if isnull(@fname,'')='' set @fname=@tbname+'.xls'
28
29 --检查文件是否已经存在30 if right(@path,1)<>'' set @path=@path+''
31 create table #tb(a bit,b bit,c bit)32 set @sql=@path+@fname33 insert into #tb exec master..xp_fileexist @sql34
35 --数据库创建语句36 set @sql=@path+@fname37 if exists(select 1 from #tb where a=1)38 set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
39 +';CREATE_DB="'+@sql+'";DBQ='+@sql40 else
41 set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
42 +';DATABASE='+@sql+'"'
43
44
45 --连接数据库46 exec @err=sp_oacreate 'adodb.connection',@obj out
47 if @err<>0 gotolberr48
49 exec @err=sp_oamethod @obj,'open',null,@constr50 if @err<>0 gotolberr51
52 /*--如果覆盖已经存在的表,就加上下面的语句53 --创建之前先删除表/如果存在的话54 select @sql='drop table ['+@tbname+']'55 exec @err=sp_oamethod @obj,'execute',@out out,@sql56 --*/
57
58 --创建表的SQL59 select @sql='',@fdlist=''
60 select @fdlist=@fdlist+',['+a.name+']'
61 ,@sql=@sql+',['+a.name+']'
62 +case
63 when b.name like '%char'
64 then case when a.length>255 then 'memo'
65 else 'text('+cast(a.length as varchar)+')'end66 when b.name like '%int' or b.name='bit' then 'int'
67 when b.name like '%datetime' then 'datetime'
68 when b.name like '%money' then 'money'
69 when b.name like '%text' then 'memo'
70 elseb.name end71 FROM syscolumns a left join systypes b on a.xtype=b.xusertype72 where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')73 and object_id(@tbname)=id74 select @sql='create table ['+@tbname75 +']('+substring(@sql,2,8000)+')'
76 ,@fdlist=substring(@fdlist,2,8000)77 exec @err=sp_oamethod @obj,'execute',@out out,@sql78 if @err<>0 gotolberr79
80 exec @err=sp_oadestroy @obj81
82 --导入数据83 set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES;IMEX=1
84 ;DATABASE='+@path+@fname+''',['+@tbname+'$])'85
86 exec('insert into'+@sql+'('+@fdlist+') select'+@fdlist+'from'+@tbname)87
88 return
89
90 lberr:91 exec sp_oageterrorinfo 0,@src out,@desc out
92 lbexit:93 select cast(@err as varbinary(4)) as错误号94 ,@src as 错误源,@desc as错误描述95 select@sql,@constr,@fdlist96 go97
98
99
100 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_exporttb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)101 drop procedure [dbo].[p_exporttb]102 GO103
104 /*--数据导出EXCEL105
106 导出查询中的数据到Excel,包含字段名,文件为真正的Excel文件107 如果文件不存在,将自动创建文件108 如果表不存在,将自动创建表109 基于通用性考虑,仅支持导出标准数据类型110
111 --邹建 2003.10(引用请保留此信息)--*/
112
113 /*--调用示例114
115 p_exporttb @sqlstr='select * from 地区资料'116 ,@path='c:',@fname='aa.xls',@sheetname='地区资料'117 --*/
118 create proc p_exporttb119 @sqlstr varchar(8000), --查询语句,如果查询语句中使用了order by ,请加上top 100percent120 @path nvarchar(1000), --文件存放目录121 @fname nvarchar(250), --文件名122 @sheetname varchar(250)='' --要创建的工作表名,默认为文件名123 as
124 declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
125 declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)126
127 --参数检测128 if isnull(@fname,'')='' set @fname='temp.xls'
129 if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')130
131 --检查文件是否已经存在132 if right(@path,1)<>'' set @path=@path+''
133 create table #tb(a bit,b bit,c bit)134 set @sql=@path+@fname135 insert into #tb exec master..xp_fileexist @sql136
137 --数据库创建语句138 set @sql=@path+@fname139 if exists(select 1 from #tb where a=1)140 set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
141 +';CREATE_DB="'+@sql+'";DBQ='+@sql142 else
143 set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
144 +';DATABASE='+@sql+'"'
145
146 --连接数据库147 exec @err=sp_oacreate 'adodb.connection',@obj out
148 if @err<>0 gotolberr149
150 exec @err=sp_oamethod @obj,'open',null,@constr151 if @err<>0 gotolberr152
153 --创建表的SQL154 declare @tbname sysname155 set @tbname='##tmp_'+convert(varchar(38),newid())156 set @sql='select * into ['+@tbname+'] from('+@sqlstr+') a'
157 exec(@sql)158
159 select @sql='',@fdlist=''
160 select @fdlist=@fdlist+',['+a.name+']'
161 ,@sql=@sql+',['+a.name+']'
162 +case
163 when b.name like '%char'
164 then case when a.length>255 then 'memo'
165 else 'text('+cast(a.length as varchar)+')'end166 when b.name like '%int' or b.name='bit' then 'int'
167 when b.name like '%datetime' then 'datetime'
168 when b.name like '%money' then 'money'
169 when b.name like '%text' then 'memo'
170 elseb.name end171 FROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype172 where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')173 and a.id=(select id from tempdb..sysobjects where name=@tbname)174
175 if @@rowcount=0 return
176
177 select @sql='create table ['+@sheetname178 +']('+substring(@sql,2,8000)+')'
179 ,@fdlist=substring(@fdlist,2,8000)180
181 exec @err=sp_oamethod @obj,'execute',@out out,@sql182 if @err<>0 gotolberr183
184 exec @err=sp_oadestroy @obj185
186 --导入数据187 set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES
188 ;DATABASE='+@path+@fname+''',['+@sheetname+'$])'189
190 exec('insert into'+@sql+'('+@fdlist+') select'+@fdlist+'from ['+@tbname+']')191
192 set @sql='drop table ['+@tbname+']'
193 exec(@sql)194 return
195
196 lberr:197 exec sp_oageterrorinfo 0,@src out,@desc out
198 lbexit:199 select cast(@err as varbinary(4)) as错误号200 ,@src as 错误源,@desc as错误描述201 select@sql,@constr,@fdlist202 go203
204 4.--在.net中导出到Excel的简单实例.205
206 (1).添加引用Microsoft Excel 11.0Object Library (在COM中)207
208 (2).在web.config的上里加209
210
211
212 //此句为了使用户能在本地打开文档,identify属性规定了身份验证的模式,一般情况下为false,这样安全性较高
213
214 (3).在Text.aspx上加Button1控件215
216 (4).在cs页面添加 usingMicrosoft.Office.Interop.Excel;217
218 (5).添加单击事件,在这里处理将数据库中的数据导入excel,代码如下:219
220 //定义方法GetData(),返回一个数据表
221 privateSystem.Data.DataTable GetData()222 {223 SqlConnection conn= new SqlConnection(@"Server=XJIE;Initial Catalog=Northwind;Uid=sa;Pwd=xjie;");224 SqlDataAdapter adapter= new SqlDataAdapter("select CompanyName 用户名,ContactTitle 联系主题,Address 住宅地址,ContactName 联系人,Phone 电话,City 城市 from Customers order by CustomerID desc",conn);225 DataSet ds= newDataSet();226 try
227 {228 adapter.Fill(ds,"Customer");229 }230 catch(Exception ex)231 {232 MessageBox.Show(ex.ToString());233 }234 return ds.Tables[0];235 }236
237
238 private void Button1_Click(objectsender, System.EventArgs e)239 {240 Application excel= newApplication();241 int rowIndex=1;242 int colIndex=0;243
244 excel.Application.Workbooks.Add(true);245
246 DataTable table=GetData();247
248 //将所得到的表的列名,赋值给单元格
249 foreach(DataColumn col intable.Columns)250 {251 colIndex++;252 excel.Cells[1,colIndex]=col.ColumnName;253 }254
255 //同样方法处理数据
256 foreach(DataRow row intable.Rows)257 {258 rowIndex++;259 colIndex=0;260 foreach(DataColumn col intable.Columns)261 {262 colIndex++;263 excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();264 }265 }266 //不可见,即后台处理
267 excel.Visible=true;268 }