导出到csv以忽略注释中的逗号和换行符

时间:2014-08-05 02:39:40

标签: c# csv

我有以下代码导出到csv罚款,但只是意识到它不会在'comments'字段文本框中处理逗号或换行符。有没有办法忽略特定字段或所有字段中的逗号和换行符?

private void saveFileDialogTrack_FileOk(object sender, CancelEventArgs e)
    {
        StringBuilder str = new StringBuilder();
        foreach (DataRow dr in this.trackDataSet.Track)
        {
            foreach (object field in dr.ItemArray)
            {
                str.Append(field.ToString() + ",");
            }
            str.Replace(",", Environment.NewLine, str.Length - 1, 1);
        }
        string name = saveFileDialogTrack.FileName;
        try
        {
            System.IO.File.WriteAllText(name, str.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        str = null;
    }

示例csv(前几个字段)Barbagallo,31,39,51.01,

        private void openFileDialogTrack_FileOk(object sender, CancelEventArgs e)
    {
        try
        {
            using (StreamReader SR = new StreamReader(openFileDialogTrack.FileName))
            {
                while (!SR.EndOfStream)
                {
                    var CSValues = SR.ReadLine().Split(',');

                    SqlCeConnection myConnection = new SqlCeConnection("Data Source = Track.sdf");
                    myConnection.Open();
                    String str = (@"INSERT INTO Track (Track, StartFinishLineNSDegrees, StartFinishLineNSMinutes, 

......................

VALUES (@track, @SFNSD, @SFNSM,

......................

                        SqlCeCommand cmd = new SqlCeCommand(str, myConnection);
                    cmd.Parameters.AddWithValue("@track", CSValues[0] == string.Empty ? (object)DBNull.Value : CSValues[0]);
                    cmd.Parameters.AddWithValue("@SFNSD", CSValues[1] == string.Empty ? (object)DBNull.Value : CSValues[1]);
                    cmd.Parameters.AddWithValue("@SFNSM", CSValues[2] == string.Empty ? (object)DBNull.Value : CSValues[2]);

2 个答案:

答案 0 :(得分:0)

根据“RFC4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files”:

  

包含换行符(CRLF),双引号和逗号的字段应括在双引号中。

为了安全起见,为了简化编码,您可以在引号中包围所有字段。

替换它:

str.Append(field.ToString() + ",");

有了这个:

str.Append(string.Format("\"{0}\",", field));

答案 1 :(得分:0)

我创建了一种方法,可以在将字符串添加到stringbuilder之前,根据需要在引号中添加文本

private string HandelQuote(string text)
        {
            if (string.IsNullOrEmpty(text)) return string.Empty;

            var containsQuote = text.Contains('"');
            var containsComma = text.Contains(',');
            var addQuote = containsComma || containsQuote;

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

            return addQuote ? "\"" + text + "\"" : text;
        }