逃避棘手的字符串CSV格式 [英] escaping tricky string to CSV format

查看:107
本文介绍了逃避棘手的字符串CSV格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建Web服务,从输出一个CSV文件,CSV文件使用带有逗号分隔符带引号的字符串。 我不能改变格式 ...

I have to create a CSV file from webservice output and the CSV file uses quoted strings with comma separator. I cannot change the format...

所以,如果我有一个字符串它成为 ...
。如果数值已经被替换,则用双引号引号。
例如,一个海峡ING 变成海峡,ING ...

So if I have a string it becomes a "string"... If the value has quotes already they are replaced with double quotes. For example a str"ing becomes "str""ing"...

不过,最近我的进口一直因为以下

However, lately my import has been failing because of the following


    失败
  • 原来输入的字符串: ,字词1,word2和......

  • 每个单引号替换为双导致:,,字词1,word2和......

  • 那么它的前缀,并写入到CVS文件之前报价后缀:,字词1,word2和......

  • original input string is: "","word1,word2,..."
  • every single quote is replaced by double resulting in: """",""word1,word2,...""
  • then its prefixed and suffixed with quote before written to CVS file: """"",""word1,word2,..."""

正如你可以看到最后的结果是这样的:

As you can see the final result is this:

""""",""word1,word2,..."""

它打破我的导入(被认为这是另一场)$ ... b $ b口认为这个问题是appereance的在原来的输入字符串。

which breaks my import (is sees it as another field)... I think the issue is appereance of "," in the original input string.

有没有对于这种情况CVS转义序列?

Is there a CVS escape sequence for this scenario?

之所以说上面休息是由于BCP映射文件( BCP实用工具用于加载CSV文件导入SQL数据库)已经终止定义为&放大器; QUOT;,&安培; QUOT; 。因此,而不是看1场它认为2 ...但我不能改变映射文件...

The reason why above breaks is due to BCP mapping file (BCP utility is used to load CSV file into SQL db) which has terminator defined as "," . So instead of seeing 1 field it sees 2...But I cannot change the mapping file...

推荐答案

我用这个代码,并一直致力于:

I use this code and it has always worked:

/// <summary>
/// Turn a string into a CSV cell output
/// </summary>
/// <param name="str">String to output</param>
/// <returns>The CSV cell formatted string</returns>
public static string StringToCSVCell(string str)
{
    bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
    if (mustQuote)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("\"");
        foreach (char nextChar in str)
        {
            sb.Append(nextChar);
            if (nextChar == '"')
                sb.Append("\"");
        }
        sb.Append("\"");
        return sb.ToString();
    }

    return str;
}

这篇关于逃避棘手的字符串CSV格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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