把数据库的数据读到Excel

把数据库的数据读到Excel
关键词: 把数据库的数据读到Excel                                           

目的
有时客户出于某种原因会要求我们能将系统的资料导出为Excel或则Access这种他们熟悉的文件格式。由于IE的打印控制比较困难,我们制作打印的时候也可以考虑提供Excel文件格式的下载,让客户在Excel中调整格式后打印。出于这些原因我们可能需要在程序中提供Excel文件格式的数据下载。

途径
导出为Excel文件有不少方法,例如:
1. 使用 Excel Automation server循环生成。
2. 生成定界符文件然后使用Excel打开,保存为Xls文件。
3. 使用XML文件作中间过程文件,然后使用Excel的OpenXML方法打开(需要Excel2002以上版本)。
4. 使用ADO.net。
我在这里要使用的方法是第四种,利用ADO.net来转换。

基本思路
我按照这么几步来实行我的计划:
1. 将SQL Server中的资料读入DataSet。
2. 使用OLEDB新建一个表(在Excel文件中就是一个Workbooks)。
3. 通过循环将DataSet的内容插入刚才建立的表中。
4. 提供刚才生成的文件的下载。
5. 删除临时生成的Excel文件。
这里有个问题,就是临时生成的Excel文件的命名冲突问题,我使用GUID来生成唯一名称。

范例代码
准备工作,我准备将虚拟目录下的Temp作为临时文件目录。

string urlPath = HttpContext.Current.Request.ApplicationPath + "/Temp/";

string physicPath = HttpContext.Current.Server.MapPath(urlPath);

string fileName = Guid.NewGuid() + ".Xls"

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";

OleDbConnection objConn 
= new OleDbConnection(connString);
OleDbCommand objCmd 
= new OleDbCommand();
objCmd.Connection 
= objConn;

建立表结构

objCmd.CommandText 
= @"CREATE TABLE 客户信息 
   (
   客户名 varchar,
   注册时间 varchar
   )
   
";

objCmd.ExecuteNonQuery();

插入新数据

//建立插入动作的Command
objCmd.CommandText = "INSERT INTO 客户资料(客户名, 生日) VALUES (@CustomerName, @RegisterTime)";
objCmd.Parameters.Add(
new OleDbParameter("@CustomerName", OleDbType.VarChar));
objCmd.Parameters.Add(
new OleDbParameter("@RegisterTime", OleDbType.VarChar));


//遍历DataSet将数据插入新建的Excel文件中,customerInfo为我们从数据库中读到的数据
foreach (DataRow row in customerInfo.Tables[0].Rows)
{    
 
for (int i=0; i {
  parm[i].Value 
= row[i]; 
 }

 objCmd.ExecuteNonQuery();
}


提供下载

HttpResponse response 
= HttpContext.Current.Response; 
response.Clear();
response.WriteFile(path 
+ fileName);
string httpHeader="attachment;filename=backup.Xls";
response.AppendHeader(
"Content-Disposition", httpHeader);
response.Flush();

System.IO.File.Delete(path 
+ fileName);//删除临时文件
response.End();


posted @ 2008-05-24 21:11  wenanry  阅读(538)  评论(0编辑  收藏  举报