良好的CSV作家为C#? [英] Good CSV Writer for C#?

查看:94
本文介绍了良好的CSV作家为C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  使用.NET编写

是否有C#什么好的CSV作家?

Are there any good CSV writers for C#?

不需要一个阅读器,只是作家。

Don't need a reader, just writer.

推荐答案

有没有太多,真的......这里的一些code我已经用了好几年:

There's not much to it, really... here's some code I've used for several years:

public static class Csv
{
    public static string Escape( string s )
    {
        if ( s.Contains( QUOTE ) )
            s = s.Replace( QUOTE, ESCAPED_QUOTE );

        if ( s.IndexOfAny( CHARACTERS_THAT_MUST_BE_QUOTED ) > -1 )
            s = QUOTE + s + QUOTE;

        return s;
    }

    public static string Unescape( string s )
    {
        if ( s.StartsWith( QUOTE ) && s.EndsWith( QUOTE ) )
        {
            s = s.Substring( 1, s.Length - 2 );

            if ( s.Contains( ESCAPED_QUOTE ) )
                s = s.Replace( ESCAPED_QUOTE, QUOTE );
        }

        return s;
    }


    private const string QUOTE = "\"";
    private const string ESCAPED_QUOTE = "\"\"";
    private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
}

您可以使用转义方法,以确保价值观正确引用。我使用这个类在一个简单的读者一起,但你说你不需要的...

You can use the Escape method to ensure that values are properly quoted. I use this class in conjunction with a simple reader, but you said you don't need that...

更新这很简单,但有更多的比的string.join 。但是,您仍然可以逃脱的东西pretty简单,如果你有值的数组(和使用C#3 +):

Update It's simple, but there is more to it than string.Join. However, you can still get away with something pretty simple, if you have an array of values (and are using C# 3+):

string.Join(",", values.Select(Csv.Escape));

这篇关于良好的CSV作家为C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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