3

我有一个使用 C# 读取的 sql08 数据库表。其中一列(College)包含一些数据有逗号的数据:Miami, FLMiami, OH,而有些则没有:USC。我的输出 .csv 将数据从包含行的逗号向右移动一列。我希望我的输出包含Miami,FL一个字段:|Miami,FL|不是|Miami| |FL|

myWriter.WriteLine("Player, Position, Current Team, College");
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("Select * FROM FootballRoster", myConnection);

myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
    string myPlayer = myReader.GetString(0);
    string myPosition = myReader.GetString(1);
    string myCurTeam = myReader.GetString(2);
    string myCollege = myReader.GetString(3);

    myWriter.WriteLine("{0}, {1}, {2}, {3},", myPlayer, myPosition, myCurTeam, myCollege);
}
4

3 回答 3

3

You can find the answer in here

Dealing with commas in a CSV file

Basically you need to escape the ',' characters. you can use '' to do it

Here you have the spec for CSV format

https://www.rfc-editor.org/rfc/rfc4180

于 2013-02-21T16:27:08.743 回答
2

尝试将值放在双引号内:

myWriter.WriteLine("\"{0}\", \"{1}\", \"{2}\", \"{3}\",", myPlayer, myPosition, myCurTeam, myCollege);
于 2013-02-21T16:27:12.797 回答
1

通常在 .CSV 中,如果字符串包含逗号,则将字段用双引号引起来。

因此,佛罗里达州迈阿密在 .CSV 文件中变为“迈阿密,佛罗里达州”。

所以你可以做类似的事情......

string myCollege = "";

if(myReader.GetString(3).Contains(","))
 {
    myCollege = "\"" + myReader.GetString(3) + "\"";
 }
else
 {
    myCollege = myReader.GetString(3);
 }
于 2013-02-21T16:29:26.130 回答