asp.net 2.0 导出DataTable到Excel中

除调用excel类,给每个单元格赋值外还可以使用另一种简单的方法

 

protected void EduceExcel(DataTable dt, string FileName)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;//设置缓冲输出
        HttpContext.Current.Response.Charset = "GB2312";//设置输出流的HTTP字符集

        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.ContentType = "application/ms-";
        //_page.EnableViewState = false;//是否保持视图状态
        HttpContext.Current.Response.Write(HTML(dt));
        HttpContext.Current.Response.End();
    }

 

 

private string HTML(DataTable dt)
    {

        StringBuilder strHtml = new StringBuilder();
        int I = dt.Columns.Count;
        strHtml.Append("<table>");
        strHtml.Append("<tr>");
        for (int j = 0; j < I; j++)
        {
            strHtml.Append("<td>" + dt.Columns[j].ColumnName + "</td>");
        }
        strHtml.Append("</tr>");
        //int ii = 1;
        foreach (DataRow dr in dt.Rows)
        {
            strHtml.Append("<tr>");
            //int I = dr.Table.Columns.Count;
            for (int i = 0; i < I; i++)
            {
                strHtml.Append(" <td>" + dr[i].ToString() + "</td>");
            }
            strHtml.Append("</tr>");
        }
        strHtml.Append("</table>");

        return strHtml.ToString();
    }

 

转载于:https://www.cnblogs.com/hdjjun/archive/2008/10/30/1323035.html

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页