본문 바로가기

코딩정보/C#

[C#] 엑셀파일 내보내기(그리드뷰)

반응형
///<summary>
/// 데이타 테이블을 엑셀로 받아온다.
///</summary>

/// <param name="dt">원본 데이타 테이블.</param>
/// <param name="columns"> 원본 데이타 테이블의 컬럼들.</param>
/// <param name="newcolumns">보여질 테이블의 컬럼들.</param>


private static void DownExcel(System.Data.DataTable dt, string[] columns, string[] newcolumns)
{
      DataGrid grid = new DataGrid();
      System.Data.DataTable targetdt = new System.Data.DataTable();

      for (int i = 0; i < columns.Length; i++)
      {
          System.Data.DataColumn column = new System.Data.DataColumn(newcolumns[i]);
          targetdt.Columns.Add(column);
       }


       for (int i = 0; i < dt.Rows.Count; i++)
       {
           object[] obj = new object[columns.Count()];

           for (int j = 0; j < columns.Length; j++)
                 obj[j] = dt.Rows[i][columns[j]];
                 targetdt.Rows.Add(obj);
       }

       grid.DataSource = targetdt;
       grid.DataBind();

       System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response;
       objResponse.ClearContent();
       objResponse.ClearHeaders();
       System.IO.StringWriter stringWrite = new System.IO.StringWriter();
       HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
       grid.RenderControl(htmlWrite);

       objResponse.ContentType = "application/vnd.msexcel";
       objResponse.AddHeader("content", "text/html; charset=utf-8");
       objResponse.AddHeader("content-disposition", "attachment; filename=SearchResults.xls");
       objResponse.Write("");
       objResponse.Write(stringWrite.ToString());
       objResponse.Flush();
       objResponse.Close();
       objResponse.End();
}

 

// 사용법

void btn_ok_Click(object sender, EventArgs e)
{
     string[] columns = { "title", "filename", "view_count", "blogurl" }; // 기존의 컬럼명
     string[] newcolumns = { "제목", "파일명", "조회수", "블로그주소"}; // 새로운 컬럼명
     System.Data.DataTable dt = ds.Tables[1]; // 데이타 테이블
     DownExcel(dt, columns, newcolumns);
}

 

 

반응형