我使用以下代码从sql server 2005读取数据并将该数据添加到list.Then我用这个列表创建一个文本文件。它工作正常。
String con1 = System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
try
{
List<string> list = new List<string>();
using (SqlConnection con = new SqlConnection(con1))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM test", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader.GetString(0);
string dept = reader.GetString(1);
list.Add(name);
list.Add(dept);
}
StreamWriter SW;
SW = File.CreateText("d:\\test.txt");
foreach (string Txt in list)
{
SW.WriteLine(Txt);
}
SW.Close();
}
}
我的问题是对齐如果我创建文本文件,记录将逐行显示。其中aaaa,cccc是name.bbbb,dddd是Dept.But它显示为,
aaaa
bbbb
cccc
dddd
但我需要名字,部门就像表格一样
aaaa bbbb
cccc dddd
怎么做?
答案 0 :(得分:2)
更改此行
list.Add(name);
list.Add(dept);
到
list.Add(name + "\t" + dept);
答案 1 :(得分:2)
for (int i = 0; i < list.Count; i += 2)
{
SW.Write(list[i]);
SW.Write("\t");
SW.WriteLine(list[i+1]);
}