Solved

How to export the contents of a datareader to a CSV file - asp.net c# and sql server

Posted on 2007-11-21
9
3,385 Views
Last Modified: 2013-11-26
I have a routine that does a dynamic search that returns a datareader.  How can I amend the following routine so that it exports the datareader fields to a csv file............
Here is the code

 IDataReader thisReader = null;
        try
        {
            try
            {

                if (isAllUserSearch == true)
                {
                    thisReader = doAllUserSearch();
                }
                else
                {
                    thisReader = doSearch();
                }

                int count = 0;
                while (thisReader.Read())
                {
                    //THIS IS WHERE I WANT TO ADD THE SQL DATAREADER FIELDS INTO A CSV FILE
                    For example, I want to have the following fields on different lines
                        (string)thisReader["Address1"];
                        (string)thisReader["Address2"];                                    
                }
                Emailer.ActiveStepIndex = 6;            }
            catch (Exception Ex)
            {
                lblMessagesProcessed.Text = "There appears to be an error whilst sending emails";
                throw;
            }
        }
0
Comment
Question by:mugsey
  • 5
  • 4
9 Comments
 
LVL 23

Expert Comment

by:Ashish Patel
ID: 20328106
Try this and note the last line comment to proceed further.
IDataReader thisReader = null;

string add1 = "";

string add2 = "";

        try

        {

            try

            {
 

                if (isAllUserSearch == true)

                {

                    thisReader = doAllUserSearch();

                }

                else 

                {

                    thisReader = doSearch();

                }
 

                int count = 0;

                while (thisReader.Read())

                {

                    //THIS IS WHERE I WANT TO ADD THE SQL DATAREADER FIELDS INTO A CSV FILE

                    For example, I want to have the following fields on different lines

                        add1 += (string)thisReader["Address1"] + ", ";

                        add2 += (string)thisReader["Address2"] + ", ";

                }
 

		if(add1.length > 2)

			add1 = add1.substring(0,add1.length-2);

		if(add2.length > 2)

			add2 = add2.substring(0,add2.length-2);
 

                Emailer.ActiveStepIndex = 6;            }

            catch (Exception Ex)

            {

                lblMessagesProcessed.Text = "There appears to be an error whilst sending emails";

                throw;

            }

        }
 

	//NOW here you have add1 and add2 string as CSV, so you can now write this to the file.

Open in new window

0
 

Author Comment

by:mugsey
ID: 20328244
Thanks for your reply, so say I wanted the csv file export to look like the following

Salutation,
FirstName,
LastName,
Address1,
Address2,
PostalCode,

How would I write the last bit of code to save the CSV to file?
0
 

Author Comment

by:mugsey
ID: 20328269
In fact the CSV file could just be
firstname, lastname, address1, address2, postcode
0
 
LVL 23

Expert Comment

by:Ashish Patel
ID: 20328293
What should you CSV file look like when you have more than 1 records. Can you please show me.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:mugsey
ID: 20328375
Well it does not matter really, so long as the user can search through the CSV

I think they want to have CSV but the ability to export to Excel also.  So it could be in either format

say

Salutation, FirstName, LastName, Address1, Address2, PostalCode

OR

Salutation,
FirstName,
LastName,
Address1,
Address2,
PostalCode,


0
 
LVL 23

Accepted Solution

by:
Ashish Patel earned 500 total points
ID: 20328644
Below is complete one for this way of csv.
Salutation, FirstName, LastName, Address1, Address2, PostalCode

last try catch has file wrtting stuff.

	IDataReader thisReader = null;

	string strvalues = "";
 

        try

        {

            try

            {

 

                if (isAllUserSearch == true)

                {

                    thisReader = doAllUserSearch();

                }

                else 

                {

                    thisReader = doSearch();

                }

 

                int count = 0;

                while (thisReader.Read())

                {
 

                        strvalues += (string)thisReader["Salutation"] + ", " + (string)thisReader["FirstName"] + ", " + (string)thisReader["LastName"] + ", ";

                        strvalues += (string)thisReader["Address1"] + ", " + (string)thisReader["Address2"] + ", " + (string)thisReader["PostalCode"] + ", ";
 
 

			if(strvalues.length > 2)

				strvalues = strvalues.substring(0, strvalues.length-2) + "\n";
 

                }

 

 

                Emailer.ActiveStepIndex = 6;            }

            catch (Exception Ex)

            {

                lblMessagesProcessed.Text = "There appears to be an error whilst sending emails";

                throw;

            }

        }

 

	try    

	{

        	FileStream fsOutput = new FileStream ("C:\\Temp\\schema.csv", FileMode.Create, FileAccess.Write);
 

		StreamWriter srOutput = new StreamWriter (fsOutput);

		srOutput.WriteLine(strvalues.ToString());

        	srOutput.Close ();

        	fsOutput.Close ();                    

    	}

    	catch (Exception ex)

    	{

        	lblMessagesProcessed.Text = "Writting file error.";

                throw;

    	}

    	finally

    	{

    	}

Open in new window

0
 

Author Comment

by:mugsey
ID: 20328678
Thanks a lot

So could I have a browse dialog box so the user can save the csv file on their desktop?
0
 
LVL 23

Expert Comment

by:Ashish Patel
ID: 20328773
Sorry mugsey, i dont know about that, but you can search it from google somewhere writting open save dialog C#. Time to go for me now. Have a nice day
0
 

Author Comment

by:mugsey
ID: 20329055
OK Thanks - I will award points as I will use it as a basis
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now