标题: 【转】 asp.net数据导出EXCEL
- temptation 2008-04-09 17:02 阅读:225
- 评论:0 | 添加评论
[图片][图片]/**//**//**//*--数据导出EXCEL
[图片]导出查询中的数据到Excel,包含字段名,文件为真正的Excel文件
[图片]如果文件不存在,将自动创建文件
[图片]如果表不存在,将自动创建表
[图片]基于通用性考虑,仅支持导出标准数据类型
[图片]--邹建 2003.10(引用请保留此信息)--*/
[图片][图片]/**//**//**//*--调用示例
[图片]p_exporttb @sqlstr='select * from 地区资料'
[图片]   ,@path='c:',@fname='aa.xls',@sheetname='地区资料'
[图片]--*/
[图片]create proc p_exporttb
[图片]@sqlstr varchar(8000),   --查询语句,如果查询语句中使用了order by ,请加上top 100 percent
[图片]@path nvarchar(1000),   --文件存放目录
[图片]@fname nvarchar(250),   --文件名
[图片]@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 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
[图片]
[图片]--创建表的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 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
[图片]FROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype
[图片]where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')
[图片]and a.id=(select id from tempdb..sysobjects where name=@tbname)
[图片]
[图片]if @@rowcount=0 return
[图片]
[图片]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 8.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

[图片]4.--在.net中导出到Excel的简单实例.
[图片](1).添加引用Microsoft Excel 11.0 Object Library (在COM中)
[图片](2).在web.config的上<system.web>里加
[图片]<identity impersonate="true"/> 
[图片]//此句为了使用户能在本地打开文档,identify属性规定了身份验证的模式,一般情况下为false,这样安全性较高
[图片](3).在Text.aspx上加Button1控件
[图片](4).在cs页面添加 using Microsoft.Office.Interop.Excel;
[图片](5).添加单击事件,在这里处理将数据库中的数据导入excel,代码如下: 
[图片]//定义方法GetData(),返回一个数据表 
[图片]private System.Data.DataTable GetData() 
[图片][图片][图片]
[图片]    SqlConnection conn= new SqlConnection(@"Server=XJIE;Initial Catalog=Northwind;Uid=sa;Pwd=xjie;"); 
[图片]    SqlDataAdapter adapter= new SqlDataAdapter("select   CompanyName 用户名,ContactTitle 联系主题,Address 住宅地址,ContactName 联系人,Phone 电话,City 城市 from Customers order by CustomerID desc",conn); 
[图片]    DataSet ds= new DataSet(); 
[图片]    
[图片]    try
[图片][图片]    [图片]{
[图片]        adapter.Fill(ds,"Customer"); 
[图片]    }
[图片]    catch(Exception ex) 
[图片][图片]    [图片]{
[图片]        MessageBox.Show(ex.ToString()); 
[图片]    }
[图片]    return ds.Tables[0]; 
[图片]}
[图片]
[图片]private void Button1_Click(object sender, System.EventArgs e) 
[图片][图片][图片]{
[图片]    Application excel= new Application(); 
[图片]    int rowIndex=1; 
[图片]    int colIndex=0; 
[图片]    
[图片]    excel.Application.Workbooks.Add(true); 
[图片]    
[图片]    DataTable table=GetData(); 
[图片]
[图片]    //将所得到的表的列名,赋值给单元格 
[图片]    foreach(DataColumn col in table.Columns)
[图片][图片]    [图片]{
[图片]        colIndex++;
[图片]        excel.Cells[1,colIndex]=col.ColumnName;
[图片]    }
[图片]    
[图片]    //同样方法处理数据 
[图片]    foreach(DataRow row in table.Rows) 
[图片][图片]    [图片]
[图片]        rowIndex++; 
[图片]        colIndex=0; 
[图片]           foreach(DataColumn col in table.Columns) 
[图片][图片]        [图片]{
[图片]            colIndex++; 
[图片]            excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString(); 
[图片]        }
[图片]    } 
[图片]    //不可见,即后台处理 
[图片]    excel.Visible=true; 
[图片]}

添加评论
返回顶部 | 返回首页