I am trying to export data into a CSV file from the SQL server. The code from this link ( Export SQL Server Data into CSV file ) is working with some except. In some rows that contain commas, the table arrangement is not correct. The code i have try
using (var connection = ConnectionToSqlServer.GetConnection())
{
connection.Open();
SqlCommand sqlCmd = new SqlCommand("Select * from dbo.Test", connection);
SqlDataReader reader = sqlCmd.ExecuteReader();
string fileName = "test.csv";
StreamWriter sw = new StreamWriter(fileName);
object[] output = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Contains(","))
{
output[i] = "\"" + reader.GetName(i) + "\"";
}
else
output[i] = reader.GetName(i);
}
}
sw.WriteLine(string.Join(",", output));
while (reader.Read())
{
reader.GetValues(output);
sw.WriteLine(string.Join(",", output));
}
sw.Close();
reader.Close();
connection.Close();
}
I am suggesting you consider below options:
,
inside it, then the generated CSV might be having an issue.while (reader.Read())
{
reader.GetValues(output);
sw.WriteLine(string.Join(",", $"\"{output}\""));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.