将sqlserver中的数据倒入Excel(c#)

将sqlserver中的数据倒入Excel(c#)


作者:ouyang76cn      出处:CSDN    虽然,sql server中的DTS也能将数据倒入Excel,但不如使用程序灵活,本程序主要代码在按钮函数内。可适应于报表开发的读取数据部分:)我删除了原程序的很多垃圾代码,只留主要起作用的代码  //加入名称空间using System.Data;using System.Data.SqlClient;  //定义方法GetData(),返回一个数据表private System.Data.DataTable GetData(){SqlConnection conn= new SqlConnection(@"Server=PXGD2;Initial Catalog=pingxiang;Uid=sa;Pwd=;");SqlDataAdapter adapter= new SqlDataAdapter("select username 用户名,catalyst_port 占用端口,home_address 住宅地址,ip_address    ip地址,phone 电话,addtime 开通日期 from userinfo where catalyst_port=1 or catalyst_port='' order by ip_address 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){Excel.Application excel= new Excel.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;        (2005-9-03:10:23)
 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 警告:持续变种木马正在发起农历新年攻势!
 您可能对 [C#] 的这些文章也感兴趣:
论C#变得越来越臃肿是不可避免的
查询IP所在区段(C#)
在C#中利用SharpZipLib进行文件的压缩和解压缩
C# - Append a host header by code in IIS
在C#中调用Microsoft.VisualBasic命名空间下的类型验证函数
使用泛型实现单例提供者(原创翻译)
C#2 anonymous methods
Master Pages: Tips, Tricks, and Traps
Microsoft .NET 框架资源基础
基于.Net平台应用程序唯一运行实例实现
.net Framework 2.0 专门提供了配置文件的操作
正确实现 IDisposable