CreatExcel()

public void CreatExcel(System.Data.DataTable dt, System.Web.UI.Page thisPage)
    {
        System.IO.StringWriter sw = new System.IO.StringWriter();
        string rowStr = "";
        //取所有列名
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            rowStr = rowStr + dt.Columns[i] + "\t";
        }
        sw.WriteLine(rowStr);
        //取每行数据
        for (int j = 0; j < dt.Rows.Count; j++)
        {
            rowStr = "";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                rowStr = rowStr + dt.Rows[j][i].ToString() + "\t";
            }
            sw.WriteLine(rowStr);
        }
        sw.Close();
        string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
        thisPage.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        thisPage.Response.ContentType = "application/ms-excel";
        thisPage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        thisPage.Response.Write(sw);
        thisPage.Response.End();
    }


 

posted @ 2009-05-21 13:37  夜色狼  阅读(152)  评论(0编辑  收藏  举报