2017-01-25 52 views
0

這裏是表結構:數據不被返回以表格形式對SqlDataReader的下載csv文件

enter image description here

這裏是代碼:

protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader) 
{ 
    StringBuilder builder = new StringBuilder(); 

    List<string> columnNames = new List<string>(); 
    List<string> rows = new List<string>(); 

    for (int i = 0; i < oDataReader.FieldCount; i++) 
    { 
     string tmpColumnName = oDataReader.GetName(i); 
     columnNames.Add(tmpColumnName); 
    } 

    builder.Append(string.Join(",", columnNames.ToArray())).Append("\n"); 

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

    while (oDataReader.Read()) 
    { 
     ////base.WriteLog(oDataReader.FieldCount + "fieldcount"); 
     for (int i = 0; i < oDataReader.FieldCount; i++) 
     { 
      object item = oDataReader[i]; 
      currentRow.Add(item.ToString()); 
     } 
    } 

    //builder.Append(string.Join("\n", rows.ToArray())).Append("\n"); 
    rows.Add(string.Join(",", currentRow.ToArray())); 
    builder.Append(string.Join(",", rows.ToArray())).Append("\n"); 

    Response.Clear(); 
    Response.ContentType = "text/csv"; 
    Response.AddHeader("Content-Disposition", "attachment;filename=pretestscore.csv"); 
    Response.Write(builder.ToString()); 
    Response.End(); 
} 

的問題是,雖然輸出

while (oDataReader.Read()) 

功能值a重新返回就像

281063,70,7091,85,TEST,200,test,NULL 

如何從表中獲取實際數據?

我的代碼中的錯誤在哪裏?

有什麼建議嗎?

回答

1
protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader) 
    { 
     string strCSV = string.Empty; 

     for (int i = 0; i < oDataReader.FieldCount; i++) 
     { 
      string tmpColumnName = oDataReader.GetName(i); 

      strCSV += tmpColumnName + ','; 
     } 

     strCSV += "\r\n"; 



     while (oDataReader.Read()) 
     { 


      for (int i = 0; i < oDataReader.FieldCount; i++) 
      { 
       object item = oDataReader[i]; 

       strCSV += item.ToString().Replace(",", ";") + ','; 

      } 


      strCSV += "\r\n"; 

     } 


     //Download the CSV file. 
     Response.Clear(); 
     Response.Buffer = true; 
     Response.AddHeader("content-disposition", "attachment;filename=pretestscore.csv"); 
     Response.Charset = ""; 
     Response.ContentType = "application/text"; 
     Response.Output.Write(strCSV); 
     Response.Flush(); 
     Response.End(); 


    } 
+0

好。正是我所說的這個 –

0

你可以直接用逗號分開,用逗號分開,用for循環或while循環。

您可以參考此代碼,你會得到的想法

string s;     
while (reader.Read()) 
{ 
    if(!String.IsNullOrEmpty(s)){ 
     s += ", "; 
    } 
    s += reader["name"].ToString(); 
} 
+0

你可以寫下來的代碼??如何? –

+0

你可以查看我編輯的答案。你需要根據自己的需要去做自己的事情。 –

+0

你能告訴我如何添加for循環? –

相關問題