2011-09-22 83 views
0
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() + ","; 
      data += SQLRD[1].ToString() + ","; 
      data += SQLRD[2].ToString() + ","; 
      data += SQLRD[3].ToString() + ","; 
      data += SQLRD[4].ToString() + ","; 
      data += SQLRD[5].ToString() + ","; 
      data += SQLRD[6].ToString() + ","; 
      data += SQLRD[7].ToString(); 
      data += "\n"; 

     } 

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

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

當前我的代碼不顯示用戶指定文件位置的對話框。它總是存儲在「C:\ download.csv」;中是「硬編碼的」。取而代之,我想用對話框。如何使用對話框下載?

+1

是U知道要保存在Web服務器上該文件並沒有下載到客戶端? –

+0

@DavidePiras,我不知道。有什麼方法可以使用對話框。我試過研究,但我不明白。這就是爲什麼我決定發佈這個問題。謝謝。我需要幫助。 – Mark20

回答

2

首先我會說不要用System.String反對contact字符串。總是使用System.Text.StringBuilder對象。

System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
while (SQLRD.Read()) 
    { 
    sb.Append(String.Format("{0},{1},{2},{3},{4},{5},{6},{7}\n", 
     SQLRD[0],SQLRD[1],SQLRD[2],SQLRD[3],SQLRD[4],SQLRD[5],SQLRD[6],SQLRD[7])); 
    } 

下載數據,

byte[] ar = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); 
Response.ClearContent(); 
Response.ClearHeaders(); 
Response.AddHeader("Content-Type", "application/octet-stream"); 
Response.AddHeader("Content-Length", ar.Length.ToString()); 
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv"); 
Response.BinaryWrite(ar); 
Response.Flush(); 
Response.End(); 
+0

感謝您的回答。我現在會嘗試這些代碼。謝謝。會讓你知道它是否有效。 – Mark20

+0

該代碼工作正常。謝謝,我真的很感激! – Mark20