Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

sql - C# SQLServer retrieving results and place in a .csv format

I had a look on the site and on Google, but I couldn't seem to find a good solution to what I'm trying to do.

Basically, I have a client server application (C#) where I send the server an SQL select statement (Connecting to SQL Server 2008) and would like to return results in a CSV manner back to the client.

So far I have the following:

if (sqlDataReader.HasRows)
{
    while(sqlDataReader.Read())
    {
       //not really sure what to put here and if the while should be there!
    }

} `

Unfortunately, I'm really new to connecting C# with SQL. I need any tips on how to simply put the results in a string in a csv format. The columns and fields are likely to be different so I cannot use the method of something[something] as I've seen in a few sites. I'm not sure if I'm being comprehensible tbh!

I would really appreciate any tips / points on how to go about this please!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a method I use to dump any IDataReader out to a StreamWriter. I generally create the StreamSwriter like this: new StreamWriter(Response.OutputStream). I convert any double-quote characters in the input into single-quote characters (maybe not the best way to handle this, but it works for me).

public static void createCsvFile(IDataReader reader, StreamWriter writer) {
    string Delimiter = """;
    string Separator = ",";

    // write header row
    for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++) {
        if (columnCounter > 0) {
            writer.Write(Separator);
        }
        writer.Write(Delimiter + reader.GetName(columnCounter) + Delimiter);
    }
    writer.WriteLine(string.Empty);

    // data loop
    while (reader.Read()) {
        // column loop
        for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++) {
            if (columnCounter > 0) {
                writer.Write(Separator);
            }
            writer.Write(Delimiter + reader.GetValue(columnCounter).ToString().Replace('"', ''') + Delimiter);
        }   // end of column loop
        writer.WriteLine(string.Empty);
    }   // data loop

    writer.Flush();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...