相信很多朋友在做GridView导出Excel功能时,像×××号这种字段的数据导出来格式是科学计数法显示而无法正常使用.
解决方法:
1.先定义格式转换方法:
文本:vnd.ms-excel.numberformat:@
日期:vnd.ms-excel.numberformat:yyyy/mm/dd
数字:vnd.ms-excel.numberformat:#,##0.00
货币:vnd.ms-excel.numberformat:¥#,##0.00
百分比:vnd.ms-excel.numberformat: #0.00%
private static void gv_ItemDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); //i表示列号,格式类型见上
}
}
2.导出Excel方法
/// <summary>
/// 将DataGrid数据导入到Excel
/// </summary>
/// <param name="dg"></param>
/// <param name="strFileName"></param>
/// <returns></returns>
public static void ExportExcel(DataTable dt, string strFileName)
{
WebCommon.WriteLogToDB("导出Excel", HttpContext.Current.Request.Url.PathAndQuery, strFileName); //写日志
System.Web.UI.WebControls.GridView gv = new GridView();
gv.RowDataBound += new System.Web.UI.WebControls.GridViewRowEventHandler(gv_ItemDataBound); //绑定格式转换方法
gv.DataSource = dt.DefaultView;
gv.DataBind();
System.Web.HttpContext obj = System.Web.HttpContext.Current;
obj.Response.Clear();
obj.Response.Buffer = true;
obj.Response.AddHeader("Content-Disposition", "p_w_upload;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls");
obj.Response.ContentEncoding = System.Text.Encoding.UTF8;
obj.Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gv.RenderControl(htw);
obj.Response.Write(sw.ToString());
obj.Response.End();
}