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

Dav*_*uli 7 c# csv

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

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

谢谢

Dro*_*ror 25

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

 ="00023423"
Run Code Online (Sandbox Code Playgroud)

CSV示例:

David,Sooo,="00023423",World
Run Code Online (Sandbox Code Playgroud)

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

  • 遗憾的是,这不再有效 - 引用现在显示为单元格的一部分。但是任何*不能成为数字*一部分的字符都会触发非数字解释,从而保留前导零。因此,您可以在前面或后面添加制表符或不间断空格 (`"\xA0"`)。如果字段以 +、-、=、@ 开头,则前置还可以防止将该字段解释为公式,因此可以减轻 CSV 注入攻击。 (2认同)

小智 7

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());
    }
Run Code Online (Sandbox Code Playgroud)

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

重要的部分:

  "=\"" + client.phone + "\"", client.name
Run Code Online (Sandbox Code Playgroud)

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


Kub*_*tek 5

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

"Some Name","'0000121212"
Run Code Online (Sandbox Code Playgroud)

Excel应该将其0000121212视为字符串.