[原创]ASP.NET MVC导出Excel 避免身份证号码格式乱码

ASP.NET MVC导出Excel 避免身份证号码格式乱码问题,

利用导出的Excel的脚本增加“vnd.ms-excel.numberformat:@”的style来解决

导出省份证号码的科学计数法的问题


 /// <summary>
 /// 导出Excel文件
 /// </summary>
 /// <param name="ls">数据集</param>
 /// <returns></returns>
 public FileResult ExportExcel(List<EmployeeExcel> ls)
 {
 var sbHtml = new StringBuilder();
 sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
 sbHtml.Append("<tr>");
 var lstTitle = new List<string> ();
 PropertyInfo[] properties = typeof(EmployeeExcel).GetProperties();
 for (int i = 0; i < properties.Length; i++)
 {
 string headName = properties[i].Name;
 Attribute attribute = Attribute.GetCustomAttribute(properties[i], typeof(DisplayNameAttribute));
 if (attribute != null)
 {
 DisplayNameAttribute displayNameAttribute = attribute as DisplayNameAttribute;
 if (displayNameAttribute != null && !string.IsNullOrWhiteSpace(displayNameAttribute.DisplayName))
 {
 headName = displayNameAttribute.DisplayName;
 }
 }

 lstTitle.Add(headName);
 }
 foreach (var item in lstTitle)
 {
 sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
 }
 sbHtml.Append("</tr>");
 for (int i = 0; i < ls.Count; i++)
 {
 sbHtml.Append("<tr>");
 for (int j = 0; j < properties.Length; j++)
 {
 string sign = j == properties.Length - 1 ? "\n" : "\t";
 object obj = properties[j].GetValue(ls[i], null);
 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;vnd.ms-excel.numberformat:@'>{0}</td>", obj);
 }
 sbHtml.Append("</tr>");
 }
 sbHtml.Append("</table>");

 //第一种:使用FileContentResult
 byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());
 DateTime time = DateTime.Now;
 String fileName = string.Format("{0}_{1}_{2}_{3}",
 time.Month, time.Day, time.Hour, time.Minute);
 return File(fileContents, "application/ms-excel", fileName+".xls");

 }
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏