• 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();
                }

  • 相关阅读:
    【POJ3237】Tree 树链剖分+线段树
    【BZOJ3531】[Sdoi2014]旅行 树链剖分+动态开点线段树
    【BZOJ4034】[HAOI2015]树上操作 树链剖分+线段树
    【BZOJ1984】月下“毛景树” 树链剖分+线段树
    【BZOJ2243】[SDOI2011]染色 树链剖分+线段树
    【BZOJ1036】[ZJOI2008]树的统计Count 树链剖分
    树形DP水题杂记
    【BZOJ1827】[Usaco2010 Mar]gather 奶牛大集会 树形DP
    【BZOJ1864】[Zjoi2006]三色二叉树 树形DP
    【BZOJ1060】[ZJOI2007]时态同步 树形DP
  • 原文地址:https://www.cnblogs.com/yshj/p/2785564.html
Copyright © 2020-2023  润新知