Dev Language/C#

엑셀 exprot

타카스 류지 2015. 2. 24. 10:34

 

 

 

 

 protected void btnExcel_Click(object sender, EventArgs e)
    {
        DataSet ds = Admin.getExcel(txtSDate.Text, txtEDate.Text, txtIdno.Text, rbtSelect.SelectedValue.ToString());
        string fileTime = DateTime.Now.ToShortDateString().Replace("-", "");
        try{
         // 기존 버퍼내용 제거
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                // 파일네임 지정
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileTime + ".xls");
                // 파일타입(데이터형식) 지정
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

                // 문자셋 지정
                HttpContext.Current.Response.Charset = "euc-kr";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("euc-kr");
                //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                //this.EnableViewState = false;

                // 문자열 기록 개체 인스턴스 생성
                System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                // html 표현 방식으로 변환
                System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

                // 엑셀생성할 새로운 그리드뷰 생성
                GridView makeGV = new GridView();

                // 생성된 데이터그리드 디자인
                makeGV.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                makeGV.HeaderStyle.BackColor = System.Drawing.Color.FromName("#E5EAEE");
                makeGV.RowStyle.HorizontalAlign = HorizontalAlign.Center;

                // 그리드뷰에 새 데이터 바인드
                makeGV.DataSource = ds;
                makeGV.DataBind();

                for (int i = 0; i < makeGV.Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        makeGV.Rows[i].Cells[j].Style.Add("mso-number-format", "\\@"); // 숫자컬럼정의
                    }
                }

                // 엑셀 Export
                makeGV.RenderControl(htmlWriter);

                HttpContext.Current.Response.Write(stringWriter.ToString());
                HttpContext.Current.Response.End();

                stringWriter.Flush();
                stringWriter.Close();

                htmlWriter.Flush();
                htmlWriter.Close();
            }

            catch (Exception ex)
            {
            }

    }