Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
# Monday, July 04, 2005

Part 1 shows us how to create CSV files in both C# and VB.NET using techniques that were used back on the old days of ADO and OLEDB but implementing them using native ADO.NET objects(IDataReader) instead of recordsets. We use a IDataReader instead of a provider specific reader (SqlDataReader, OleDbDataReader) for usability of code. This makes our function not provider dependent.

Here is the solution for both C# and VB.NET projects
CreateCSVCS.zip (20.05 KB)
CreateCSVVB.zip (21.06 KB)

The C# source code for part 1 is listed below:

private void createButton_Click(object sender, System.EventArgs e)
        {    
            //create the command object for the connection to the database
            //also assign the sql statement to be use in querying our database
            SqlCommand command = new SqlCommand(sqlStatementField.Text,new SqlConnection(connectionStringField.Text));
            //open the connection
            command.Connection.Open();
            //create the sqlreader that would hold the result set
            SqlDataReader reader = command.ExecuteReader();
            //set the conttent type of the file to be downloaded
            Response.ContentType = "Application/x-msexcel";
            //add the response headers
            Response.AddHeader("content-disposition", "attachment; filename=\"" + filenameField.Text + "\"");
            //add the contents of the result set to the response stream
            Response.Write( ToCSV(reader) );
            //close the connection
            command.Connection.Close();
            //end the http response
            Response.End();
        }

        public static string ToCSV(IDataReader iDr)
        {
            //declare the stringbuilder object that would serve as the placeholder for our data
            StringBuilder sb = new StringBuilder();
            //check to see if there the reader has columns
            if(iDr.FieldCount != 0)
            {
                //loop thru each column
                for(int i = 0; i <= iDr.FieldCount -1; i++)
                {
                    //check to see if we are on the last column
                    // this is necessary so that we could append the nextline symbol
                    if(i<iDr.FieldCount -1)
                    {
                        //if not the last column, append the column name and a ','
                        sb.Append(iDr.GetName(i) + ",");
                    }
                    else
                    {
                        //append the last column name then append a carriage return and line feed
                        sb.Append(iDr.GetName(i));
                        sb.Append("\r\n");
                    }
                }
                
                //loop until the record reaches eol(end of line)
                while(iDr.Read())
                {
                    //loop thru each column, this is necessesary so that we could map
                    //the columns to their proper place
                    for(int i = 0; i <= iDr.FieldCount -1; i++)
                    {
                        //check to see if we are on the last column
                        //this is necessary so that we could append the nextline symbol
                        if(i<iDr.FieldCount -1)
                        {
                            //if not the last column, append the column value and a ','
                            sb.Append(iDr.GetValue(i) + ",");
                        }
                        else
                        {
                            //append the last column value then append a carriage return and line feed
                            sb.Append(iDr.GetValue(i));
                            sb.Append("\r\n");
                        }
                    }
                }
            }
        //return our stringbuilder
        return sb.ToString();
        }

Here is the VB.NET version of for part 1:

Private Sub createButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles createButton.Click
'create the command object for the connection to the database
'also assign the sql statement to be use in querying our database
Dim command As SqlCommand = New SqlCommand(sqlStatementField.Text, New SqlConnection(connectionStringField.Text))
'open the connection
command.Connection.Open()
'create the sqlreader that would hold the result set
Dim reader As SqlDataReader = command.ExecuteReader()
'set the conttent type of the file to be downloaded
Response.ContentType = "Application/x-msexcel"
'add the response headers
Response.AddHeader("content-disposition", "attachment; filename=""" & filenameField.Text & """")
'add the contents of the result set to the response stream
Response.Write(ToCSV(reader))
'close the connection
command.Connection.Close()
'end the http response
Response.End()
End Sub

Public Function ToCSV(ByVal iDr As IDataReader) As String
'declare the stringbuilder object that would serve as the placeholder for our data
Dim sb As StringBuilder = New StringBuilder
'check if there are columns on the reader
If (iDr.FieldCount <> 0) Then
'loop to the first column to the last column of our reader
For i As Integer = 0 To iDr.FieldCount - 1
'check to see if we are on the last column
'this is necessary so that we could append the nextline symbol
If (i < iDr.FieldCount - 1) Then
'if not the last column, append the column name and a ','
sb.Append(iDr.GetName(i) & ",")
Else
'append the last column name then append a carriage return and line feed
sb.Append(iDr.GetName(i))
sb.Append(vbCrLf)
End If
Next

'loop until the record reaches eol(end of line)
Do While (iDr.Read())
'loop thru each column, this is necessesary so that we could map
'the columns to their proper place
For i As Integer = 1 To iDr.FieldCount - 1
'check to see if we are on the last column
'this is necessary so that we could append the nextline symbol
If (i < iDr.FieldCount - 1) Then
'if not the last column, append the column value and a ','
sb.Append(iDr.GetValue(i) & ",")
Else
'append the last column value then append a carriage return and line feed
sb.Append(iDr.GetValue(i))
sb.Append(vbCrLf)
End If
Next
Loop
End If
'return our stringbuilder
Return sb.ToString()
End Function

Here is the solution for both C# and VB.NET projects
CreateCSVCS.zip (20.05 KB)
CreateCSVVB.zip (21.06 KB)

On part 2, i'm going to show you how to use DataTables instead of DataReaders toAccomplish this task.

Monday, July 04, 2005 8:24:24 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET
Tracked by:
"Part 2: Creating CSV in ASP.NET" (keithrull.com: a technology hub for geeks) [Trackback]
"Part 2: Creating CSV in ASP.NET" (Keith Rull) [Trackback]
"Part 3: Creating CSV in ASP.NET" (keithrull.com: a technology hub for geeks) [Trackback]
"Part 3: Creating CSV in ASP.NET" (Keith Rull) [Trackback]
"buy celexa" (online) [Trackback]
"buy avodart" (online) [Trackback]
"diet plan" (online) [Trackback]
"bay area photographer" (bay area photographer) [Trackback]
"her first audition" (her first audition) [Trackback]
"buyphentermineprozac" (buyphentermineprozac) [Trackback]
"annuncio affitti isernia" (annuncio affitti isernia) [Trackback]
"paul posey tallahassee florida" (paul posey tallahassee florida) [Trackback]
"sauna mista milano" (sauna mista milano) [Trackback]
"una sera nel parco" (una sera nel parco) [Trackback]
"Executive Office Furniture" (Executive Office Furniture) [Trackback]
"georgia bulldog" (georgia bulldog) [Trackback]
"pacifica armoire" (pacifica armoire) [Trackback]
"vecchie mature grasse donne" (vecchie mature grasse donne) [Trackback]
"cd organizers" (cd organizers) [Trackback]
"gadget audi" (gadget audi) [Trackback]
"female body builders posing" (female body builders posing) [Trackback]
"congelatore da incasso" (congelatore da incasso) [Trackback]
"cameriere in autoreggenti" (cameriere in autoreggenti) [Trackback]
"Sports Betting Rss Feed" (Sports Betting Rss Feed) [Trackback]
"albuquerque respiratory jobs va medical center" (albuquerque respiratory jobs v... [Trackback]
"tiaras and headpieces" (tiaras and headpieces) [Trackback]
"used kountry aire camper trailer" (used kountry aire camper trailer) [Trackback]
"bollente fantastico nubile" (bollente fantastico nubile) [Trackback]
"invisibile pulcino dildo" (invisibile pulcino dildo) [Trackback]
"bitches getting fuck" (bitches getting fuck) [Trackback]
"fotografico" (fotografico) [Trackback]
"how to make a sword" (how to make a sword) [Trackback]
"sms gratis cellulare" (sms gratis cellulare) [Trackback]
"teen dating forum" (teen dating forum) [Trackback]
"west virginia dui law" (west virginia dui law) [Trackback]
"poor girls for marriage" (poor girls for marriage) [Trackback]
"viaggi abruzzo" (viaggi abruzzo) [Trackback]
"thumbzilla" (online) [Trackback]
"areosmith" (online) [Trackback]
"enamal car paint" (online) [Trackback]
"rv classified ads" (online) [Trackback]
"transunion" (online) [Trackback]
"featherlite trailers" (online) [Trackback]
"novastar mortgage" (online) [Trackback]
"trish mcevoy" (online) [Trackback]
"slipknot drum solo" (online) [Trackback]
"Brand ultram order ultram tramadol pain medicine." (Order tramadol.) [Trackback]
http://9lk-free-porn.info/26412464/erotic-stories-proctologist.html [Pingback]
http://9lr-free-porn.info/28844559/index.html [Pingback]
http://9lk-free-porn.info/55566052/index.html [Pingback]
http://9ln-free-porn.info/59233724/index.html [Pingback]
http://9lo-free-porn.info/30939130/index.html [Pingback]
http://9lq-free-porn.info/69717664/index.html [Pingback]
http://9ls-free-porn.info/80804435/free-cartoon-sex-now.html [Pingback]
http://9ls-free-porn.info/67964213/wooton-bassett-canal.html [Pingback]
http://9ls-free-porn.info/19580559/jimie-lynn-spears-nude.html [Pingback]
http://9lq-free-porn.info/09968940/requirements-analysis-and-design.html [Pingback]
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Keith Rull
Sign In
Statistics
Total Posts: 271
This Year: 0
This Month: 0
This Week: 0
Comments: 182
Themes
Pick a theme:
All Content © 2010, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)