如何安排下载的信息以适应行?

时间:2011-09-22 05:03:10

标签: c# asp.net sql-server-2008 download

SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
SqlCommand Command = connection.CreateCommand();

SqlDataReader SQLRD;

Command.CommandText = "Select * from Attendance";

connection.Open();
SQLRD = Command.ExecuteReader();

string data = "";

while (SQLRD.Read())
{
    data += SQLRD[0].ToString()+  "\n";
    data += SQLRD[1].ToString() + "\n";
    data += SQLRD[2].ToString() + "\n";
    data += SQLRD[3].ToString() + "\n";
    data += SQLRD[4].ToString() + "\n";
    data += SQLRD[5].ToString() + "\n";
    data += SQLRD[6].ToString() + "\n";
    data += SQLRD[7].ToString() + "\n";
}

SQLRD.Close();
connection.Close();

string filename = @"C:\download.csv";//specified location
FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();

这是我到目前为止所做的。目前,在点击下载时,所有信息都显示在1个单列中,并且不会分成行。我需要知道如何将它们排成行。我也可以知道当用户点击下载时如何显示对话框。目前该文件只存储在指定位置?

1 个答案:

答案 0 :(得分:1)

导出为.csv格式时,您希望在列之间放置逗号(,),并在行之间返回行(\ n)。目前,您在每个列之间进行换行。尝试这样的事情:

while (SQLRD.Read())
{
     data += SQLRD[0].ToString() + ",";
                   //              ^^^ note the change from '\n' to ','
     data += SQLRD[1].ToString() + ",";
     data += SQLRD[2].ToString() + ",";
     ...
     data += SQLRD[7].ToString(); // final column doesn't need a ','
     data += "\n"; // final line separator for the entire row
}

致以最诚挚的问候,