.Net

DataTable Excel 출력

무명시인 2011. 3. 24. 14:03
DataTable 을 Excel 로 출력할때 쓰는 함수 입니다.
간단하게 작성해봤습니다.
        


public static void ExportExcel(DataTable dt)
{
    StringBuilder sb = new StringBuilder();

    sb.Append("");

    // head
    sb.Append("");

    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.AppendFormat("", dt.Columns[i].ColumnName);
    }
    sb.Append("");

    // body
    foreach (DataRow dr in dt.Rows)
    {
        sb.Append("");

        for (int j = 0; j < dt.Columns.Count; j++) sb.AppendFormat("", dr[j]);

        sb.Append("");
    }

    sb.Append("
{0}
{0}
"); string name = string.Format("엑셀_{0}", DateTime.Now.Ticks.ToString()); HttpContext.Current.Response.ContentType = "application/vnd.msexcel"; HttpContext.Current.Response.AddHeader("content", "text/html; charset=utf-8"); HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", HttpUtility.UrlEncode(name))); HttpContext.Current.Response.Write(sb.ToString()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); HttpContext.Current.Response.End(); }