web 方法代码整理

一、导出表格数据到excel.

 public static void ExportExcel(System.Data.DataTable dt, string sequenceHeader)
    {
        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
        stringBuilder.Append("<html><head><meta http-equiv="content-type" content="text/html; charset=gb2312"/>");
        stringBuilder.Append("<table border=1 style='font-size:12px'>");
        stringBuilder.Append("<tr>");
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            string columnName = dt.Columns[i].ColumnName;
            if (!(columnName == "InstanceId"))
            {
                stringBuilder.AppendFormat("<th>{0}</th>", columnName);
            }
        }
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            stringBuilder.Append("<tr>");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string arg = string.Empty;
                arg = dt.Rows[i][j].ToString();
                stringBuilder.AppendFormat("<td>{0}</td>", arg);
                
            }
            stringBuilder.Append("</tr>");
        }
        stringBuilder.Append("</tr>");
        stringBuilder.Append("</table>");
        stringBuilder.Append("</body></html>");
        byte[] array = new byte[stringBuilder.Length];
        array = System.Text.Encoding.GetEncoding(936).GetBytes(stringBuilder.ToString());
        string text3 = System.Guid.NewGuid().ToString();
        string str = text3;
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("Content-Length", array.Length.ToString());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(str) + ".xls");
        HttpContext.Current.Response.OutputStream.Write(array, 0, array.Length);
        HttpContext.Current.Response.End();
    }
ExportExcel
原文地址:https://www.cnblogs.com/gudaozi/p/9632605.html