.NET 中一种将DataTable表下载到本地Excel文件方法

代码清单:

 

protected void BtnDown_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = ForConfirmValidORDown(true);

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (dt != null && dt.Rows.Count > 0) 
        {
            sb.Append("<div><table border='1'>");

            //表头
            sb.Append("<tr>");
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append("<th>" + dt.Columns[i].ColumnName + "</th>");
            }
            sb.Append("</tr>");

            string trBg = "";
            //记录
            foreach (DataRow dr in dt.Rows)
            {
                if (trBg == "")
                {
                    trBg = "#F1EED5";
                }
                else {
                    trBg = "";
                }

                sb.Append("<tr style='background:" + trBg + "'>");
                object[] objs = dr.ItemArray;
                foreach (object obj in objs)
                {
                    string str = obj.ToString();
                    sb.Append("<th>" + str + "</th>");
                }
                sb.Append("</tr>");
            }

            sb.Append("</table></div>");
        }

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(downFileName));
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/excel";
        Response.Write(sb.ToString());
    }
    catch (Exception ex)
    {
        DoException(ex);
    }
    Response.End();
}

posted on 2010-04-21 17:11  迎-客-松  阅读(467)  评论(0编辑  收藏  举报

导航