在显示CSV逗号不使用逗号 [英] Show comma in CSV without using the comma character

查看:340
本文介绍了在显示CSV逗号不使用逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录CSV格式:我们写出来一定日志操作。然而,一个字段允许用户输入,我需要确保的如果他们进入我们解析出来,并与东西取代它的该领域的一个逗号,比如说,Excel将能够读取并显示在它的地方逗号(所以CSV读者不会认为它是一列的末尾)。

I have a log in CSV format we write out for a certain logging operation. However, one of the fields allows user input and I need to make sure that if they enter a comma in the field that we parse it out and replace it with something that, say, Excel will be able to read and show a comma in its place (so the csv reader will not think it is the end of a column).

目前我与&放大器更换逗号;#44; 但这显示为文字字符串在Excel中。

Currently I replace the comma with , but this is shows as a literal string in Excel.

有没有显示CSV文件逗号,而无需使用实际的逗号字符的标准方式?即使是只使用Excel工作会的工作,因为我们的大多数客户的解决方案将使用Excel查看该文件。

Is there a standard way to display a comma in a CSV file without using the actual comma character? Even a solution that only works with excel will work, since most of our customers will be using Excel to view this file.

推荐答案

处理嵌入的逗号,最好的办法是适当引用CSV文件:

The best way to handle embedded commas is to properly quote the CSV file:


  • 包含逗号列应该被引用

  • 包含报价应具备的报价逃脱
  • 引用列

例如:

张三张三,小,乔,的哥史密斯,JR。

Joe Smith, "Joe Smith, Jr.", "Joe ""The Man"" Smith, Jr."

我写了一个扩展方法,可以帮助解决这个问题:

I wrote an extension method that helps solve this:

static public string CsvQuote(this string text)
{
    if (text == null) return string.Empty;

    bool containsQuote = false;
    bool containsComma = false;
    int len = text.Length;

    for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
    {
        char ch = text[i];
        if (ch == '"')
        {
            containsQuote = true;
        }
        else if (ch == ',' || char.IsControl(ch))
        {
            containsComma = true;
        }
    }

    bool mustQuote = containsComma || containsQuote;

    if (containsQuote)
    {
        text = text.Replace("\"", "\"\"");
    }

    // Quote the cell and replace embedded quotes with double-quote or just return as is
    return mustQuote ? "\"" + text + "\"" : text;
}



用法:

logger.Write(myString.CsvQuote());

var csv = string.Join(",", listOfStrings.Select(CsvQuote))

这篇关于在显示CSV逗号不使用逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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