第一次尝试在c#中构建csv文件时,代码如下:
string FilePath = @"C:\Users\me\Downloads\csvfiles\test-" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".csv";
string delimit = ",";
List<string> cells = new List<string>();
Console.WriteLine("Gathering the data...");
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT id, name FROM contacts";
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Building the csv file");
while (reader.Read())
{
AddCell((IDataRecord)reader, cells);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cells.Count; i++)
{
sb.AppendLine(string.Join(delimit, cells[i]));
}
File.WriteAllText(FilePath, sb.ToString());
/*Method to add each record to the list*/
public static void AddCell(IDataRecord record, List<string> cells)
{
cells.Add(record[0].ToString());
cells.Add(record[1].ToString());
}
麻烦的是,它将所有内容附加到新行,它不会将记录[1]移动到下一列并开始新行......
答案 0 :(得分:1)
您的For循环对于您要执行的操作不正确。
替换:
for (int i = 0; i < cells.Count; i++)
{
sb.AppendLine(string.Join(delimit, cells[i]));
}
使用
int i = 0;
while (i < cells.Count)
{
sb.AppendLine(string.Join(delimit, cells[i],cells[i+1]));
i = i + 2;
}
答案 1 :(得分:0)
string FilePath = @"C:\Users\me\Downloads\csvfiles\test-" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".csv";
string delimit = ",";
List<string> cells = new List<string>();
Console.WriteLine("Gathering the data...");
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT id, name FROM contacts";
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Building the csv file");
while (reader.Read())
{
AddCell((IDataRecord)reader, cells);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cells.Count; i++)
{
if (cells[i].Equals("\n"))
{
sb.Append(Environment.NewLine);
}
else
{
sb.Append(cells[i]);
}
}
File.WriteAllText(FilePath, sb.ToString());
/*Method to add each record to the list*/
public static void AddCell(IDataRecord record, List<string> cells)
{
cells.Add(record[0].ToString());
cells.Add(",");
cells.Add(record[1].ToString());
cells.Add("\n");
}
不像你的@cvraman那么优雅,但它也有效:)我将使用你的解决方案。