using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace TestDataTableToExcel {
public partial class _Default : System.Web.UI.Page {
protected void Page_Load ( object sender,EventArgs e ) {
//数据源
DataTable table = new DataTable ();
table.Columns.Add(new DataColumn("序号"));
table.Columns.Add (new DataColumn ("姓名"));
table.Columns.Add (new DataColumn ("性别"));
for (int i = 0; i < 10; i++) {
DataRow row = table.NewRow ();
row[0] = (i + 1);
row[1] = "张三悄悄悄悄悄悄悄悄悄悄悄";
row[2] = "男";
table.Rows.Add (row);
}
//绑定到列表控件
DataGrid dataGrid = new DataGrid ();
dataGrid.DataSource = table;
dataGrid.HeaderStyle.Font.Bold = true;
dataGrid.DataMember = table.TableName;
dataGrid.DataBind ();
//所有列全部左对齐
dataGrid.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
//应用单个列的样式要循环了
//dataGrid.Items[0].Cells[1].BackColor = System.Drawing.Color.FromKnownColor (System.Drawing.KnownColor.Firebrick);
//dataGrid.Items[2].BackColor = System.Drawing.Color.ForestGreen;
//输出
Response.Clear ();
Response.Buffer = true;
Response.Charset = "GBK";
Response.AppendHeader ("Content-Disposition","attachment;filename=Data.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
Response.ContentType = "application/ms-excel";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter ();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter (oStringWriter);
dataGrid.RenderControl (oHtmlTextWriter);
Response.Output.Write (oStringWriter.ToString ());
Response.Flush ();
Response.End ();
}
}
}