首页 新闻 会员 周边

asp.net C#中查询并从sql中将数据导出到excel

0
悬赏园豆:50 [已解决问题] 解决于 2012-09-19 11:47

将数据查出来并点击导出按钮导出到excel中

求详细代码

c.w.Li的主页 c.w.Li | 初学一级 | 园豆:155
提问于:2011-07-05 14:34
< >
分享
最佳答案
0

先引用 Microsoft.Office.Interop.Excel

再如下导入命名空间:

using System.Data.Common;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
示例代码如下:

using (DbConnection connection = new SqlConnection("server=.; user id=sa; 
password=***; database=northwind"))
{
connection.Open();

DbCommand command
= connection.CreateCommand();
command.CommandType
= System.Data.CommandType.Text;
command.CommandText
= "select EmployeeId, FirstName, LastName, Title
from dbo.Employees";

var reader
= command.ExecuteReader();

Excel.Application application
= new Excel.Application();
Excel.Workbook workbook
= application.Workbooks.Add();
Excel.Worksheet worksheet
= workbook.ActiveSheet as Excel.Worksheet;

var index
= 1;
while (reader.Read())
{
worksheet.Cells[index,
1] = reader.GetInt32(0).ToString();
worksheet.Cells[index,
2] = reader.GetString(1);
worksheet.Cells[index,
3] = reader.GetString(2);
worksheet.Cells[index,
4] = reader.GetString(3);
index
++;
}
reader.Close();

workbook.SaveAs(
@"d:\employees.xlsx");
workbook.Close();
application.Quit();

connection.Close();
}
收获园豆:50
鹤冲天 | 老鸟四级 |园豆:2379 | 2011-07-05 15:34
其他回答(2)
0
邀月 | 园豆:25475 (高人七级) | 2011-07-05 15:23
可能只能支持2003以下版本
支持(0) 反对(0) arechs | 园豆:205 (菜鸟二级) | 2011-07-05 15:52
0
杯具程序员 | 园豆:1718 (小虾三级) | 2011-07-29 17:02
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册