在SqlDataReader上以下表csv文件的表格格式不返回数据

时间:2017-01-25 06:12:42

标签: c# asp.net sqldatareader

这是表结构:

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())

函数返回的值就像

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

如何从表中获取实际数据?

我的代码中的错误在哪里?

有什么建议吗?

2 个答案:

答案 0 :(得分: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();


    }

答案 1 :(得分:0)

您可以使用以for循环或while循环分隔的逗号直接编写代码。

您可以参考此代码,您将获得想法

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