从控制台应用程序生成CSV或Excel

时间:2017-10-25 13:14:02

标签: c# excel csv

我正在尝试创建一个C#控制台应用程序,我希望看到我的输出与mssql格式相同。我将输出作为csv或excell文件。你能指导我如何安排我的输出吗?

SqlConnection conn = new SqlConnection("Server=sad;Database=*;User Id=*;Password=*;");
conn.Open();
string query = "select computername, version, os, from testdatabase";
SqlCommand cmd = new SqlCommand(query, conn);
                SqlDataReader reader = cmd.ExecuteReader();
 while (reader.Read())
                    {
//something should be here but I dont know what
}

reader.Close();
conn.Close();

1 个答案:

答案 0 :(得分:-1)

创建CSV文件的一个简单示例如下:

List<string> outLines = new List<string>();

while (reader.Read())
{
   outLines.add(reader.GetValue(0).ToString() + "," +
                reader.GetValue(1).ToString() + "," +
                reader.GetValue(2).ToString());
}

System.IO.File.WriteAllLines("C:/outFile.csv",outLines.ToArray());