protected void Button1_Click(object sender, EventArgs e)
{
#region 設定轉出來的Excel表頭欄位
DataGrid dgExcel = new DataGrid();
dgExcel.ID = "__dgExcel";
dgExcel.AutoGenerateColumns = false;
//設定欄位
BoundColumn bc;
//訂單日期
bc = new BoundColumn();
bc.DataField = "TRAN_DATE";
bc.HeaderText = "訂單日期";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//CAMPAIGN_CODE
bc = new BoundColumn();
bc.DataField = "CAMPAIGN_CODE";
bc.HeaderText = "活動代碼";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//AGT
bc = new BoundColumn();
bc.DataField = "AGENT_ID";
bc.HeaderText = "AGT";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//訂單編號(直效交易序號)
bc = new BoundColumn();
bc.DataField = "TRAN_NO";
bc.HeaderText = "直效交易序號";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//統一產品編號
bc = new BoundColumn();
bc.DataField = "DTL_PRODUCT_CODE";
bc.HeaderText = "統一產品編號";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//產品名稱
bc = new BoundColumn();
bc.DataField = "PROD_ITEM_NAME";
bc.HeaderText = "產品名稱";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//售價
bc = new BoundColumn();
bc.DataField = "DTL_ITEM_INAMT";
bc.HeaderText = "售價";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//是否為贈品
bc = new BoundColumn();
bc.DataField = "PROD_ITEM_TYPE_NAME";
bc.HeaderText = "是否為贈品";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//數量
bc = new BoundColumn();
bc.DataField = "DTL_ITEM_NUM";
bc.HeaderText = "數量";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
//小計
bc = new BoundColumn();
bc.DataField = "DTL_TOTAL";
bc.HeaderText = "小計";
this.SetStyle(bc);
dgExcel.Columns.Add(bc);
#endregion
//取資料
TranOrder to = new TranOrder();
DataSet ds = to.GetTranOrderData(.....);
//基本上只要你能夠將資料放到DataSource,就可以轉出來
dgExcel.DataSource = ds;
dgExcel.ShowFooter = false;
dgExcel.DataBind();
//設定轉出的檔名
string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
string style = "<style> .text { mso-number-format:\\@;
} </script>";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "UTF-8";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
dgExcel.RenderControl(hw);
Response.Write("<head><meta http-equiv='content-type'
content='text/html; charset=UTF-8'></head>");
Response.Write(tw.ToString());
}
private void SetStyle(BoundColumn bc) {
this.SetStyle(bc, true , true);
}
private void SetStyle(BoundColumn bc , bool IsText , bool SetHeight)
{
bc.HeaderStyle.Font.Size = FontUnit.Point(10);
//bc.HeaderStyle.Wrap = false;
bc.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
bc.HeaderStyle.CssClass = "text";
bc.ItemStyle.Font.Size = FontUnit.Point(10);
//bc.ItemStyle.Wrap = false;
bc.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
if (IsText == true)
bc.ItemStyle.CssClass = "text";
if(SetHeight == true)
bc.ItemStyle.Height = Unit.Parse("60px");
}
沒有留言:
張貼留言