导出到 Excel,同时使用 Gridview 和 LINQ 保持起始零



当我将模型导出到 excel 时,我似乎失去了起始零。我的数据库中的某些值具有例如"0345"或"0001"的值。当我将它们导出到 excel 时,Excel 工作表显示"345"或"1"。如何保持前导零?我的应用程序使用的是 MVC 5,并且我正在使用 LINQ 语句填充gv.DataSourcedb.lookup_client_name.ToList();我阅读了其他文章,这些文章指出将值设置为字符串,开头带有'(单引号)或在字符串前添加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("/");
}

你正在使用一个"廉价的技巧"来创建一个excel,你不是在创建一个excel,你正在创建一个HTML页面,Excel试图这样做,最好将其转换为excel工作表。

也就是说,当Excel将这些值视为数值时,它们会转换为数字,这就是删除前导零的原因。

基本上不可能使用 HTML 技巧定义单元格格式,因此,如果您确实需要保留这些零,则必须创建一个真正的 XML 文件并指定数据类型或在这些值之前或之后添加一些字符以避免 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();

最新更新