• asp.net webform/mvc导出Excel通用代码


    最近将自己在项目中经常用到的excel导出方法分析如下,如有不妥之处望他人指出,如果有更好的方法希望展示出来互相学习。

    //导出事件

     protected void btnexcel_Click(object sender, EventArgs e)

    {

        //定义导出Excel的标题

      List<string> tabletitle = new List<string>();
      tabletitle.Add("企业注册号");
      tabletitle.Add("企业名称");
      tabletitle.Add("企业开业日期");

      DataTable dt=GetCompanyList();

         Print(dt, tabletitle);

    }

    /// <summary>
    /// 输出Excel
    /// </summary>
    /// <param name="dt">数据</param>
    /// <param name="title">表头</param>
    public static void Print(DataTable dt, List<String> title)
    {
    StringBuilder sHtml = new StringBuilder();
    sHtml.Append("<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>");
    sHtml.Append("<table border=1>");
    sHtml.Append("<tr style='background-color:#D8DFF1;'>");
    foreach (String s in title)
    {
    sHtml.Append("<td>");
    sHtml.Append(s);
    sHtml.Append("</td>");
    }
    sHtml.Append("</tr>");
    foreach (DataRow row in dt.Rows)
    {
    sHtml.Append("<td style="vnd.ms-excel.numberformat:@">"); //注:style="vnd.ms-excel.numberformat:@"  去除科学计数法表示方式,以文本方式显示。
    sHtml.Append(row["zch"].ToString());
    sHtml.Append("</td>");
    sHtml.Append("<td>");
    sHtml.Append(row["qymc"].ToString());
    sHtml.Append("</td>");
    sHtml.Append("<td>");
    sHtml.Append(row["kyrq"] != null && row["kyrq"].ToString() != "" ? Convert.ToDateTime(row["kyrq"]).ToString("yyyy-MM-dd") : "");
    sHtml.Append("</td>");
    sHtml.Append("</tr>");
    }
    sHtml.Append("</table>");

    System.Web.HttpContext.Current.Response.Charset = "GB2312";
    System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
    System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode( DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xls", System.Text.Encoding.UTF8).ToString());
    System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
    System.Web.HttpContext.Current.Response.Output.Write(sHtml);
    System.Web.HttpContext.Current.Response.Flush();
    System.Web.HttpContext.Current.Response.End();

    }

  • 相关阅读:
    轻松自动化---selenium-webdriver(python) (八)
    Ubuntu 18.04 LTS 启用 WakeOnLAN
    lower_bound 和 upper_bound
    [LeetCode 201.] Bitwise AND of Numbers Range
    [LeetCode 162.] Find Peak Element
    [LeetCode 33. 81. 153. 154.] 旋转数组中的二分查找
    C++ unordered_map 的一个疑问
    [LintCode 386.] 最多有k个不同字符的最长子字符串
    [LintCode 550.] 最常使用的K个单词II
    [LintCode 1029.] 寻找最便宜的航行旅途(最多经过k个中转站)
  • 原文地址:https://www.cnblogs.com/lihaishu/p/4353558.html
Copyright © 2020-2023  润新知