导出到Excel,同时使用Gridview和LINQ保持开始零
当我将我的模型导出到excel时,我似乎失去了开始的零。 我的数据库中的某些值的值为“0345”或“0001”。 当我将它们导出为excel时,excel表格显示“345”或“1”。 我如何保持领先的零? 我的应用程序使用MVC 5,并使用LINQ语句db.lookup_client_name.ToList();
我已阅读其他文章,其中指出,在开始时将值设置为具有'
(单引号) '
的string,或者在string之前添加\t
。 我如何通过LINQ语句来实现这一点? 我的代码在下面…
public ActionResult ExportToExcel(string Value) { var gv = new GridView(); gv.DataSource = db.lookup_client_name.ToList(); gv.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=LookupClientName_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + ".xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter objStringWriter = new StringWriter(); HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter); gv.RenderControl(objHtmlTextWriter); Response.Output.Write(objStringWriter.ToString()); Response.Flush(); Response.End(); return RedirectToAction("/"); }
您正在使用“廉价技巧”创build一个excel,您不创buildexcel,您正在创build一个HTML页面,Excel试图将其转换为Excel表格。
说,因为Excel把这些值看作一个数字值,所以他们被转换成数字,这就是为什么前导零被删除。
基本上用HTML技巧来定义单元格格式是不可能的,所以如果你真的需要保留这些零值,或者创build一个真正的XML文件并指定数据types或者在这些值之前或之后添加一些字符以避免Excel检测它作为一个数字。
如果你想将char添加到值,我不能写出确切的代码,因为我没有lookup_client_name
内容结构,但这里是一个例子,它会给你的一般想法:
//this class represents the structure of the data of the lookup_client_name content public class RowContent { public string SomeProperty{ get; set; } public string PreserveValues{ get; set; } } //... gv.DataSource = db.lookup_client_name. Select(i => new { SomeProperty = i.SomeProperty, PreserveValues = "'" + i.PreserveValues + "'" }).ToList();