Click here to Skip to main content
Click here to Skip to main content

Reading Online CSV File and Manage it into Microsoft SQL Database

By , 7 Aug 2012
 

Introduction

For software developers who have been working for long days, there might be a need to read online files from desktop or web applications and then store the data in local system or database. It is a little complex if you have no experience in it. There are several ways in which you can do it. In this demonstration, I will explain it from my experience to handle this type of situation.

Background

I have an Excel file online, the URL is http://velocitypath.com/odesk/buildings.csv. I need to read this file and manage it in Microsoft SQL Server database. The structure of the Excel file is given below:

Figure 1

Let’s Get Started

To store data from Excel file to database, it is required to create a table structure in Microsoft SQL Server database.

  • Open Microsoft SQL Server Management Studio
  • Create a table structure like below:

Figure 2

Open Microsoft Visual Studio 2010

  • Create a New Project (File>New>Project>Visual C#>Windows Form Application)
  • Name it as ReadingOnlineExcelFile

Figure 3

By default, the new project includes a form called ReadExcel.cs. Design the form like below:

Figure 4

To read the online file, you need to send web request. After processing successful web request, the web server will return a web response. To accomplish this, you need to use HttpWebRequest, HttpWebResponse classes. And WebRequest class is used to create a web request. All these classes can be found in System.Net namespace.

using System.Net;

Now, create a method for handling web request and to get counter response. Our intention is to get StreamReader object as a return value of this method. So you need to include:

using System.IO;
#region Method

private StreamReader GetStream()
        {
            String strURL = String.Empty;
            strURL = "http://velocitypath.com/odesk/buildings.csv";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);

            StreamReader reader;

            using (HttpWebResponse response =(HttpWebResponse)request.GetResponse())
            {
                reader = new StreamReader(response.GetResponseStream());
            }

            return reader;
        }

#endregion Method

In the above method, WebRequest.Create() is used to create web request, to get response from web request GetResponse(), to read stream from web response, GetResponseStream() is used.

Add System.Configuration reference:

Figure 5

Add the following namespace for data and SQL Operation.

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

Add the following code in button click event:

private void btnReadExcel_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection
            (ConfigurationManager.ConnectionStrings["SQLConnection"].ToString()))
            {
                conn.Open();

                StreamReader streamReader;

                streamReader = GetStream();

                streamReader.ReadLine();
                while (!streamReader.EndOfStream)
                {
                    String []row = streamReader.ReadLine().ToString().Split(',');

                    SqlCommand selectCommand;
                    selectCommand = new SqlCommand("SELECT * FROM Location
                    WHERE Latitude=@Latitude AND Longitude=@Longitude", conn);

                    selectCommand.Parameters.Add("@Latitude",
                    SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[0]);
                    selectCommand.Parameters.Add("@Longitude",
                    SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[1]);

                    SqlDataReader reader = selectCommand.ExecuteReader();

                    if (!reader.HasRows)
                    {
                        reader.Close();

                        SqlCommand insertCommand;
                        insertCommand = new SqlCommand("INSERT INTO Location
                        (Latitude,Longitude,BuildingName)
                        VALUES(@Latitude,@Longitude,@BuildingName)", conn);

                        insertCommand.Parameters.Add("@Latitude",
                        SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[0]);
                        insertCommand.Parameters.Add("@Longitude",
                        SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[1]);
                        insertCommand.Parameters.Add("@BuildingName",
                        SqlDbType.VarChar, 100).Value = row[2].ToString();

                        int intResult;
                        intResult = insertCommand.ExecuteNonQuery();
                    }
                }
            }
        }

In the above code, the following GetStream() returns Stream from web request.

  streamReader = GetStream();
  streamReader.ReadLine();

The above line of code reads line from stream.

Figure 6

Add line from stream into array for easy manipulation.

String []row = streamReader.ReadLine().ToString().Split(',');

Figure 7

Now check whether data already exists in the database.

SqlCommand selectCommand;
selectCommand = new SqlCommand
     ("SELECT * FROM Location WHERE Latitude=@Latitude AND Longitude=@Longitude", conn);

     selectCommand.Parameters.Add("@Latitude",
     SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[0]);
     selectCommand.Parameters.Add("@Longitude",
     SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[1]);

     SqlDataReader reader = selectCommand.ExecuteReader();

     if (!reader.HasRows)
     {
     }

If not, then insert data into database.

reader.Close();

SqlCommand insertCommand;
insertCommand = new SqlCommand("INSERT INTO Location
                (Latitude,Longitude,BuildingName) VALUES
                (@Latitude,@Longitude,@BuildingName)", conn);

insertCommand.Parameters.Add("@Latitude",
SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[0]);
insertCommand.Parameters.Add("@Longitude",
SqlDbType.Decimal, 20).Value = Convert.ToDecimal(row[1]);
insertCommand.Parameters.Add("@BuildingName",
SqlDbType.VarChar, 100).Value = row[2].ToString();

int intResult;
intResult = insertCommand.ExecuteNonQuery();

Here is the result from the database:

Figure 8

Conclusion

By reading this article, you can create your online file reading application. I think this may help you in software development and professional work.

History

  • 28th March, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abdul Quader Mamun
Founder
Bangladesh Bangladesh
Member
I have been developing software/web application since 2002 mainly on Microsoft technologies. I am a MCSD and MCTS. I have developed a wide range of Web, Desktop and Mobile applications.

I am vast experience with Telerik technologies.

I am also experience with other technologies.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionOnline ExcelmemberIgor Petrushenko3 Nov '12 - 22:24 
I highly recommend you trying MyTaskHelper.com online database. It also allows import from Excel to online database
GeneralOk as an excercise but...memberdave.dolan8 Aug '12 - 6:30 
Since you have SQL Management Studio... just click on Import Data wizard and you can use XLS or csv, with no code at all Smile | :)
GeneralRe: Ok as an excercise but...memberAbdul Quader Mamun8 Aug '12 - 16:13 
Yes, But sometimes its need to modified downloaded value then insert into SQL. Smile | :)
GeneralMy vote of 3membercjb1107 Aug '12 - 21:08 
Well presented, but apart from reading the .csv via http not much to recommend.
 
There are better generic csv reader examples around.
Questioncan i read xlsx from your codememberMember 894239223 Jul '12 - 4:08 
Hi can i read xlsx excel format ?measn you have used .csv file to read likewise i can read xlsx format?if you can provide code means it will be very helpful for me
GeneralMy vote of 1memberWooln30 Aug '11 - 20:57 
so easy.
GeneralOther solutionmemberCikaPero10 Apr '11 - 22:24 
Unfortunately reading xls and xlsx files is much harder than csv files.
 
If you need to import Excel file to a database and already have ADO.NET code entities in place (DataSets, DataTables, DataAdapters) you can do this task trivially with this Excel C# / VB.NET library.
 
Here is a sample Excel C# code how to import Excel to DataTable (after which you can easily transfer DataTable to database with DataAdapter):
 
ExcelFile ef = new ExcelFile();
 
// Depending on the format of the input file, you need to change this:
DataTable dataTable = new DataTable();
dataTable.Columns.Add("FirstName", typeof(string));
dataTable.Columns.Add("LastName", typeof(string));
 
// Load Excel file.
ef.LoadXls("FileName.xls");
 
// Select the first worksheet from the file.
ExcelWorksheet ws = ef.Worksheets[0];
 
// Extract the data from the worksheet to the DataTable.
// Data is extracted starting at first row and first column for 10 rows or until the first empty row appears.
ws.ExtractToDataTable(dataTable, 10, ExtractDataOptions.StopAtFirstEmptyRow, ws.Rows[0], ws.Columns[0]);

General5 Star ArticlememberCode Hungery (Rashed Nadeem)5 Apr '11 - 0:46 
Good one
Rashed

General[My vote of 1] Misleading article titlememberPaulLinton4 Apr '11 - 12:25 
That's a csv you are reading. It's not an Excel file. Excel is just one of many applications which can read csv files. Notepad can read a csv. A less misleading name for the article would be 'Reading csv files into a database'
GeneralMy vote of 5memberSureshDeyna29 Mar '11 - 16:07 
Good work.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 8 Aug 2012
Article Copyright 2011 by Abdul Quader Mamun
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid