2011年8月4日 星期四

[.NET] DataTable 匯出 Excel

專案中常會需要匯出Excel
所以就寫了這段程式供以後使用




    public static void CreateExcel(DataTable dt, string fileName)
    {
        StringBuilder sb = new StringBuilder();

        // Print Header
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append(dt.Columns[i].ColumnName);
            sb.Append("\t");
        }
        sb.Append("\n");

        // Print Content
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sb.Append(dt.Rows[i][j]);
                sb.Append("\t");
            }
            sb.Append("\n");
        }

        string temp = string.Format("attachment;filename={0}", fileName);
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.AppendHeader("Content-disposition", temp);
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Write(sb.ToString());
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }

沒有留言:

張貼留言