在c#中写入CSV时,数字字段会丢失前导零

我正在使用一个ASP.NET应用程序将我的客户数据导出为CSV,我需要我的客户电话号码与前导零。 我需要电话号码没有“ – ”且没有引用,由于我的应用程序的性质,我不能使用第三方产品,如EPPLUS。 我试图放一个空格,让CSV“理解”我需要电话号码作为文本,但这似乎不对。

我想知道如何使excel包括领先的零,而不使用第三方产品。

谢谢

使用以下格式更改csv中保存的数据:

="00023423" 

CSV示例:

 David,Sooo,="00023423",World 

这将在excel中显示00023423而不是23423。

 public void CreatingCsvFiles(Client client) { string filePath = "Your path of the location" + "filename.csv"; if (!File.Exists(filePath)) { File.Create(filePath).Close(); } string delimiter = ","; string[][] output = new string[][]{ new string[]{ "=\"" + client.phone + "\"", client.name } }; int length = output.GetLength(0); StringBuilder sb = new StringBuilder(); for (int index = 0; index < length; index++) sb.AppendLine(string.Join(delimiter, output[index])); File.AppendAllText(filePath, sb.ToString()); } 

灵感来自http://softwaretipz.com/c-sharp-code-to-create-a-csv-file-and-write-data-into-it/

重要的部分:

  "=\"" + client.phone + "\"", client.name 

如果电话号码是int,当然你添加.toString()。

使用前置’(单引号)将电话号码打印为CSV,如下所示:

 "Some Name","'0000121212" 

Excel应将此0000121212视为字符串。

如果你已经知道手机里面多少号码,你可以这样做

phoneNumber.ToString("000000000000")

在这个例子中,我认为phoneNumber是一个int ,所需的数字长度是12