在ASP.NET中实现数据导出到Excel,并推毁服务器端的Excel进程

http://fzl-x.com/index.php?fromuid=28

1.在服务器端设置Excel应用程序访问权限。

(1)运行dcomcnfg.exe。

(2)组件服务→计算机→我的电脑→DCOM配置。

(3)右击Microsoft Excel应用程序→属性→安全→启动和激活权限→自定义→编辑。

(4)添加ASPNET用户。

2.在ASP.NET Web应用程序添加引用。

(1)右击创建的应用程序→添加引用→COM选项卡。

(2)依次添加Microsoft Office 11.0 Object Library、Microsoft Excel 11.0 Object Library。(这里用的是Microsoft Office 2003)

3.实现代码。

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using Excel;

using System.Runtime.InteropServices;

namespace MyWeb

{

/// <summary>

/// 导出Excel实例。

/// </summary>

public class OutToExcel : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button btnOutToExcel;

[DllImport("User32.dll", CharSet = CharSet.Auto)]

public static extern int GetWindowThreadProcessId(IntPtr hwnd,out int ID);

private void Page_Load(object sender, System.EventArgs e)

{

// 在此处放置用户代码以初始化页面

}

#region Web 窗体设计器生成的代码

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。

//

InitializeComponent();

base.OnInit(e);

}

/// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()

{

this.btnOutToExcel.Click += new System.EventHandler(this.btnOutToExcel_Click);

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

private void btnOutToExcel_Click(object sender, System.EventArgs e)

{

//生成数据集

SqlConnection conn = new SqlConnection("Persist Security Info=false;Data Source=.;Initial Catalog=Northwind;User );

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers",conn);

DataSet ds = new DataSet();

da.Fill(ds);

conn.Close();

Excel.Application ExcelApp = new ApplicationClass();

//获取Excel进程

IntPtr t = new IntPtr(ExcelApp.Hwnd);

int k = 0;

GetWindowThreadProcessId(t,out k);

System.Diagnostics.Process P = System.Diagnostics.Process.GetProcessById(k);

_Workbook ExcelxBk = ExcelApp.Workbooks.Add(Type.Missing);

_Worksheet ExcelxSt = (_Worksheet)ExcelxBk.ActiveSheet;

//导出字段名称

for(int col = 1;col < ds.Tables[0].Columns.Count;col = col + 1)

{

ExcelxSt.Cells[1,col] = ds.Tables[0].Columns[col - 1].ColumnName;

}

//导出数据

for(int row = 1;row < ds.Tables[0].Rows.Count;row = row + 1)

{

for(int col = 1;col < ds.Tables[0].Columns.Count;col = col + 1)

{

ExcelxSt.Cells[row + 1,col] = ds.Tables[0].Rows[row - 1][col - 1].ToString();

}

}

ExcelxSt.Columns.AutoFit(); //设置列宽度

string ExcelFileName = DateTime.Now.ToShortDateString().Replace("-","") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".xls"; //导出Excel的文件名

string ExcelFullName = Server.MapPath(".") + "/" + ExcelFileName; //导出Excel的物理路径

ExcelxBk.SaveCopyAs(ExcelFullName); //保存Excel文件

//关闭、释放资源,并推毁Excel进程

ExcelxBk.Close(false,null,null);

ExcelApp.Quit();

GC.Collect();

P.Kill();

//下载Excel文件到客户端

Response.WriteFile(ExcelFullName);

string HttpHeader = "attachment;filename=" + ExcelFileName;

Response.AppendHeader("Content-Disposition",HttpHeader);

Response.Flush();

Response.Clear();

System.IO.File.Delete(ExcelFullName); //在服务器端删除导出的Excel文件

}

}

}

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1489528