asp.net GridView导出Excel的数值乱码问题
例如订单编号 20140117163511109 和身份证号130637198501020039 )的数据会变成 2.01401E+16
,如果改为数字格式 则成 20140117163511100 和 130637198501020000 该怎么解决
------解决方案--------------------GridView 输出到 Excel 并进行格式化处理
在我们把 GridView 上的数据导入到Excel的时候,如果遇到比较长的数字字符串,比如身份证号码,就会在Excel里当成数字看待,并转换成科学计数法的格式,造成数据的丢失,下面这个方法就解决了这个问题,并示例如何进行其它的格式化。
查看例子
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = this.CreateDataSource();
GridView1.DataBind();
}
}
System.Data.DataTable CreateDataSource()
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("身份证号码", typeof(string)));
dt.Columns.Add(new System.Data.DataColumn("图书单价", typeof(decimal)));
dt.Columns.Add(new System.Data.DataColumn("购买数量", typeof(Int32)));
dt.Columns.Add(new System.Data.DataColumn("总价格", typeof(decimal)));
for (int i = 0; i < 6; i++)
{
dr = dt.NewRow();
dr[0] = "123456789123456789123456789";
dr[1] = 100 * i / 3.0;
dr[2] = i + 5;
dr[3] = (decimal)dr[1] * (Int32)dr[2];
dt.Rows.Add(dr);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}