如何通过c#在excel中显示前导零 [英] how to show leading zero in excel through c#

查看:147
本文介绍了如何通过c#在excel中显示前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将数据表的内容导出为ex​​cel时,

第一列的前导0将被截断。有没有办法防止这种情况发生?

When I export the contents of a datatable to excel, the leading 0s of the
first column are truncated. Is there a way to keep this from happening?

推荐答案

导出到excel时,在插入值之前添加\t

例如:

While exporting to excel, adding "\t" before the value being inserted
for example:
string test = "000456";
string insertValueAs = "\t" + test;



字符串测试将被视为字符串值而不是整数值。因此,它将保留前导零。

让我知道它是否有帮助。


the string test would then be considered as a string value and not an integer value. Thus, it would retain the leading zeros.
Let me know if it helps or not.


你能做的最好的事情是将列格式转换为Text

这可以通过



完成以下我将C1列的格式转换为Text

The best you could do is to convert the column format to Text
That can be done by

In the following I am converting the format of the C1 column to Text
range["C1"].NumberFormat="@";
range["C1"].Value="00129";/*Then you have to specify the value*/  





以上将给出你分配给列的确切值。



您还可以在下面查看其他格式,如Pincode,Creditcard数字格式

http://office.microsoft.com/en-sg/excel-help/keep -leading-zeros-in-number-codes-HA010342581.aspx [ ^ ]


最好的方法是将列格式化为数字,具有适当数量的前导零 - 这样您仍然可以将其用作数值。

这将创建一个新文件,第一列格式化为显示两位数,前导零:

The best way to do it is to format the column as a number, with the appropriate number of leading zeros - that way you can still use it as a numeric value.
This creates a new file, with the first column formatted to show two digits, with a leading zero:
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook wb = excel.Workbooks.Add(1);
Excel.Worksheet ws = (Excel.Worksheet) wb.Sheets[1];
ws.Cells[1, 1].EntireColumn.NumberFormat = "00";
wb.SaveAs(@"D:\Temp\aaexcel.xlsx");

但您可以改为打开现有文件并以完全相同的方式应用格式。

But you can open an existing file instead and apply the formatting in exactly the same way.


这篇关于如何通过c#在excel中显示前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆