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 System.Configuration;
namespace CommonFunction
{
	/// <summary>
	/// excel 的摘要说明。
	/// </summary>
	public class excel : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button btnGetExcel;
		protected System.Web.UI.WebControls.DataGrid dgExcel;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			DataSet objDataset = new DataSet();
			SqlConnection objConn = new SqlConnection();
			objConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionSqlServer"].ToString());
			objConn.Open();
			SqlDataAdapter objAdapter = new SqlDataAdapter("Select top 5 * from customers where country='USA'",objConn);
			objAdapter.Fill(objDataset);	
			DataView oView = new DataView(objDataset.Tables[0]);
			dgExcel.DataSource = oView;
			dgExcel.DataBind();
			objConn.Close();
			objConn.Dispose();
			objConn = null;
			if(Request.QueryString["bExcel"] == "1")
			{
				Response.ContentType = "application/vnd.ms-excel";
				
				Response.Charset = "";

				//关闭 ViewState
				EnableViewState = false;
				System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
				System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
				//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
				//获取control的HTML
				dgExcel.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
				// 把HTML写回浏览器
				Response.Write(tw.ToString());
				Response.End();
			}

		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN：该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnGetExcel.Click += new System.EventHandler(this.btnGetExcel_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnGetExcel_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("excel.aspx?bExcel=1");
		}

	}
}
