您的位置:首页 > 编程语言 > C#

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

2012-10-15 12:03 519 查看
在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方法是网上找的,来源记不清了,行绑定事件的里的内容是自已写的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: