C# DataTable导出EXCEL后身份证等信息显示乱码解决

来源:互联网 发布:自作头像软件 编辑:程序博客网 时间:2024/04/29 10:53

在DataTable导出EXCEL后发现有些格式显示有问题,比如身份证号码等大于11位的数字显示为科学计数法、13681-1等 带中划线的两段数字显示为日期格式等。

处理方法如下:

        public static void DataTable2Excel(System.Data.DataTable dtData)        {            System.Web.UI.WebControls.DataGrid dgExport = null;            // 当前对话             System.Web.HttpContext curContext = System.Web.HttpContext.Current;            // IO用于导出并返回excel文件             System.IO.StringWriter strWriter = null;            System.Web.UI.HtmlTextWriter htmlWriter = null;            if (dtData != null)            {                // 设置编码和附件格式                 curContext.Response.ContentType = "application/vnd.ms-excel";                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");                curContext.Response.Charset = "gb2312";                // 导出excel文件                 strWriter = new System.IO.StringWriter();                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid                 dgExport = new System.Web.UI.WebControls.DataGrid();                dgExport.DataSource = dtData.DefaultView;                dgExport.AllowPaging = false;                dgExport.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(dgExport_ItemDataBound);                dgExport.DataBind();                // 返回客户端                 dgExport.RenderControl(htmlWriter);                curContext.Response.Clear();                curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString());                curContext.Response.End();            }        }        protected static void dgExport_ItemDataBound(object sender, DataGridItemEventArgs e)        {            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)            {                foreach (TableCell cell in e.Item.Cells)                {                    if (Regex.IsMatch(cell.Text.Trim(), @"^\d{12,}$") || Regex.IsMatch(cell.Text.Trim(), @"^\d+[-]\d+$"))                    {                        cell.Attributes.Add("style", "vnd.ms-excel.numberformat:@");                    }                }            }        }

在DataGrid的行绑定事件给单元格加上样式就可以了。


DataTable2Excel方法是网上找的,来源记不清了,行绑定事件的里的内容是自已写的。

原创粉丝点击