1. 程式人生 > >datatable匯出EXCEL

datatable匯出EXCEL

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 ();

        }
    }
}