导出到excel时将数字转换为文本

时间:2012-05-22 08:30:51

标签: c# excel

我在网格视图中显示我的数据(以逗号分隔的数字),并根据需要发生。但是,当我将其导出为ex​​cel时,则值会根据显示

进行更改

例如我的值是901155465,978785496,987458986 然后它显示为901,155,465,978,785,496,987,458,986

这就是我将数据集传递给excel的方法。我知道我们也可以渲染HTML,但我只需要传输数据。


GridView GridView1 = new GridView();
GridView1.DataSource = myDataSet;
GridView1.DataBind();
string style = @" .text { mso-number-format:\@; }  "; 
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
esponse.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter s_Write = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter h_write = new HtmlTextWriter(s_Write);
GridView1.ShowHeader = true;
GridView1.RenderControl(h_write);
Response.Write(style); 
Response.Write(s_Write.ToString());
Response.End();

似乎excel将数字视为一个数字并在适当的位置添加逗号。

是否有任何显示数据的解决方案,如gridview所示。

提前致谢

5 个答案:

答案 0 :(得分:9)

试试这个:

_worksheet.Cells[1, 1] = "=\"" + YOUR_VALUE + "\"";

这就是我使用Interop.Excel的方式

Excel将忽略(=),因为它启动一个公式,双引号将告诉excel将该值用作String。

答案 1 :(得分:8)

您也可以尝试导出excel样式表:

mso-number-format:"0"   NO Decimals

http://cosicimiento.blogspot.fr/2008/11/styling-excel-cells-with-mso-number.html

因此您需要将其写入Response

// ...
string style = @"<style> td { mso-number-format:"0"; } </style> ";
// Style is added dynamically
Response.Write(style);
Response.Write(s_Write.ToString());
// ...

答案 2 :(得分:2)

试试这个工作正常

for(int i = 0; i&lt; gvExportExcel.Rows.Count; i ++)  gvExportExcel.Rows [i] .Cells [0] .Attributes.Add(“style”,“mso-number-format:\ @”);

答案 3 :(得分:0)

这个问题让我困扰了一年,这对我有所帮助。我尝试了很多解决方案stackoverflow.com,但它没有帮助。希望这有助于某人

Dim formatRange As Excel.Range
formatRange = xlWorkSheet.Range("a1", "b1")
formatRange.NumberFormat = "@"

将数据放入单元格A1

xlWorkSheet.Cells(1, 1) = "098"

或者如果您要从datagridview复制

xlWorkSheet.PasteSpecial("Text", False, False, Type.Missing, Type.Missing, Type.Missing, True)

http://vb.net-informations.com/excel-2007/vb.net_excel_page_format.htm 祝你好运。

答案 4 :(得分:0)

"\"\t" + value?.ToString() + "\"";

任何人都可以使用这行代码,如果你需要转换和导出数字或任何值。

对于我的情况,     value =“13291440533000102”; 当我尝试使用StreamWriter导出时,该值以CSV格式正确导出。但在打开.csv文件时,excel将值视为数字。由于该数字超过16个字符,因此转换为13291440533000100.最后一个字符被更改。我已经解决了这个问题。