【问题标题】:How to write data on multiple lines BUT within the same cell of csv?如何在csv的同一个单元格中写入多行数据?
【发布时间】:2011-06-29 05:43:21
【问题描述】:

我想用 C# 创建一个 csv 文件。

我有一些数据要写在多行但在同一个单元格中。

例如 如果我有以下三句话,

Sample sentence 1. This is second sample sentence. and this is third sentence.

我想在 csv 文件的单个单元格中写下所有这三个句子,但我希望其中三个在单独的行上。

我的预期输出是:

Sample sentence 1.
This is second sample sentence.
and this is third sentence.

目前我正在尝试通过在两个句子之间使用\n 字符来实现这一点,但是当我这样做时,所有三个句子都在单独的行中。

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: c# csv


    【解决方案1】:

    quote Wikipedia

    嵌入换行符的字段必须 用双引号括起来 字符。

    例如:

    1997,Ford,E350,"Go get one now
    they are going fast"
    

    【讨论】:

      【解决方案2】:

      您也许可以更改应用程序用于解析 csv 文件中的行的标记,但根据 definition of the csv file format,文件中的行用于表示生成的表格数据中的行。

      【讨论】:

        【解决方案3】:
        string input = "...";
        
        var r = input.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) // split by dot (have you any better approaches?)
                     .Select(s => String.Format("\"{0}.\"", s.Trim())); // escape each with quotes
        
        input = String.Join(Environment.NewLine, r); // break by line break
        

        【讨论】:

          【解决方案4】:

          始终将您的描述放在“\”之间,例如:CsvRow.Add("\"" + ID + " : " + description + "\"");

          【讨论】:

            【解决方案5】:
            string filePath = @"d:\pandey.csv";
                    StringBuilder outString=new StringBuilder();
                    outString.Append("\""); //double quote 
                    outString.Append("Line 1, Hi I am line 1 of same cell\n");
                    outString.Append("Line 2 Hi I am line 2 of same cell\n");
                    outString.Append("Line 3 Hi I am line 3 of same cell\n");
                    outString.Append("Line 4 Hi I am line 4 of same cell");
                    outString.Append("\""); //double quote             
                    File.WriteAllText(filePath, outString.ToString());
            

            【讨论】:

            • 请在您的代码中添加注释以解释您的答案
            【解决方案6】:

            CSV 代表“逗号分隔值”,它只是对文本文件的描述。如果你想导入到 Excel 中,然后只有一行中的句子,你应该尝试:

            Environment.NewLine
            

            插入一个简单的/n

            【讨论】:

              猜你喜欢
              • 2021-01-03
              • 1970-01-01
              • 2022-08-19
              • 1970-01-01
              • 1970-01-01
              • 2019-07-04
              • 2022-01-18
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多