zoukankan      html  css  js  c++  java
  • DataTable导出excel 设置单元格格式

      public static void DataTableExcel(System.Data.DataTable dtData, String FileName)
            {
                System.Web.UI.WebControls.GridView dgExport = null;
                System.Web.HttpContext curContext = System.Web.HttpContext.Current;
                System.IO.StringWriter strWriter = null;
                System.Web.UI.HtmlTextWriter htmlWriter = null;

                if (dtData != null)
                {
                    //设置编码和附件格式 作用是中文文件名乱码
                    //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)
                    curContext.Response.ContentType = "application/ms-excel"; // "application nd.ms-excel";
                    curContext.Response.ContentEncoding = System.Text.Encoding.Default;
                    curContext.Response.Charset = "gb2312";
                    curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                    //导出Excel文件
                    strWriter = new System.IO.StringWriter();
                    htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                    //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
                    dgExport = new System.Web.UI.WebControls.GridView();
                    dgExport.DataSource = dtData;
                    dgExport.AllowPaging = false;
                    dgExport.DataBind();

          //设置导出格式为文本格式防止丢失数据
                        dgExport.Attributes.Add("style", "vnd.ms-excel.numberformat:@");

                        //设置excel单元格格式防止转换数据丢失数字
                        //for (int i = 0; i < dtData.Rows.Count; i++)
                        //{
                        //    for (int j = 0; j < dtData.Columns.Count; j++)
                        //    {
                        //        dgExport.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                        //    }
                        //}

                    //下载到客户端
                    dgExport.RenderControl(htmlWriter);
                    curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />"+strWriter.ToString());
                    curContext.Response.End();
                }

  • 相关阅读:
    Codeforces Round #352 (Div. 1) B. Robin Hood (二分)
    Codeforces Round #209 (Div. 2) D. Pair of Numbers (模拟)
    Kattis
    kattis Curious Cupid (莫队算法)
    HYSBZ
    SPOJ NETADMIN
    day26-2 基于TCP协议的套接字编程
    day26-1 TCP三次握手和四次挥手
    day25-2 OSI协议和socket抽象层
    day25-1 网络架构与互联网组成
  • 原文地址:https://www.cnblogs.com/yshj/p/2785564.html
Copyright © 2011-2022 走看看