• C# 将datatable导出成Excel


    public void Result( )
    {

    try
    {
    StringBuilder sql = new StringBuilder();
    List<SqlParameter> parameters = new List<SqlParameter>();

    sql.Append(@"sql 查询语句");
    DataTable dt = DbHelperSQL.Query(sql.ToString()).Tables[0];
    StringBuilder TableHead = new StringBuilder();
    StringBuilder TableFoot = new StringBuilder();
    TableHead.Append("<tr style="font-weight: bold; white-space: nowrap;">")
    .Append("<td rowspan ="2"></td></tr>")
    .Append("<tr></tr>");
    TableFoot.Append("<tr><td colspan = "4">导出时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + "</td></tr>");
    DataTableToExcel(dt, TableHead.ToString(), TableFoot.ToString(), name + "汇总_" + DateTime.Now.ToString("yyyyMM"));

    }
    catch (Exception ex)
    {

    }
    }

    /// <summary>
    /// DataTable导出Excel
    /// </summary>
    /// <param name="data">集合</param>
    /// <param name="ChartHead">表头</param>
    /// <param name="fileName">文件名称</param>
    public static void DataTableToExcel(DataTable data, string ChartHead, string ChartFoot, string fileName)
    {
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
    HttpContext.Current.Response.Charset = "Utf-8";
    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", Encoding.UTF8));
    StringBuilder sbHtml = new StringBuilder();
    sbHtml.AppendLine("<meta http-equiv="Content-Type" content="text/html; charset=utf-8">");
    sbHtml.AppendLine("<table cellspacing="0" cellpadding="5" rules="all" border="1">");
    //写出表头
    sbHtml.AppendLine(ChartHead);
    string NumberAsTextExp = "vnd.ms-excel.numberformat:@";
    //写数据
    foreach (DataRow row in data.Rows)
    {
    sbHtml.Append("<tr>");
    for (int i = 0; i < row.ItemArray.Count(); i++)
    {
    if (row[i].GetType() == typeof(string))
    {
    sbHtml.Append("<td style='" + NumberAsTextExp + "'>").Append(row[i]).Append("</td>");
    }
    else
    {
    sbHtml.Append("<td>").Append(row[i]).Append("</td>");
    }
    }
    sbHtml.AppendLine("</tr>");
    }
    //写汇总行
    sbHtml.AppendLine(ChartFoot);
    sbHtml.AppendLine("</table>");
    HttpContext.Current.Response.Write(sbHtml.ToString());
    HttpContext.Current.Response.End();
    }

  • 相关阅读:
    员工年龄排序之桶排序
    滑动窗口中最大值
    开机自动启动Tomcat
    基于RXTX的串口通讯 windows64位系统可用
    一些SQL
    Java 实现文件上传、下载、打包、文件copy、文件夹copy。
    Page-encoding specified in XML prolog (UTF-8) is different from that specified in page directive (utf-8)
    Java -> 把Excel表格中的数据写入数据库与从数据库中读出到本地 (未完善)
    (转)解决:本地计算机 上的 OracleOraDb10g_home1TNSListener服务启动后停止
    PHP、Java对称加密中的AES加密方法
  • 原文地址:https://www.cnblogs.com/hexi707/p/10727889.html
Copyright © 2020-2023  润新知