Wednesday, May 25, 2011

Read Data From an Excel File (.xlsx) in ASP.NET


In this article, we will see how to display data from an Excel spreadsheet using ASP.NET. We will connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then display the data in a GridView. Let us get started.

Step 1: Open Visual Studio > File > New >Website > Under Templates, click ASP.NET WebSite and choose either Visual C# as the language. Select a location and click Ok.

Step 2: We will create two excel sheets and add them to the project. One excel sheet will be created in Office 2003(.xls) and the other one using Office 2007(.xlsx). Add 4 columns called EID, EName, Age and City to the ‘Sheet1’. Also add some data into the columns. Once these excel files are created, add them to your project. To add them to the project, right click project > Add Existing Item > Add the two excel files.

Step 3: We will now create a web.config file if not already there to store the connection string information. Right click project > Add New Item > Web.config. Add the following entries to the file

      <connectionStrings>
            <add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sample1.xls;Extended Properties=Excel 8.0"/>
            <add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties=Excel 12.0"/>
      connectionStrings>

Ensure that you mentioned the whole path of the excel file i.e.c:/MyProject/sample1.xls etc..

As you can observe, the connection string for xlsx (Excel 2007) contains Microsoft.ACE.OLEDB.12.0 as the provider. This is the new Access database engine OLE DB driver and is also capable of reading Excel 2003.

Step 4: Add a GridView to the Default.aspx page. We will extract  data from the excel file and bind it to the GridView.

Step 5: Let us now create a connection to the excel file and extract data from it. Before that add a reference to System.Data.OleDb;

Please mention the exact sheet name + $ in query as in the excel file.

C#
    protected void Page_Load(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
        // Create the connection object
        OleDbConnection oledbConn = new OleDbConnection(connString);
        try
        {
            // Open connection
            oledbConn.Open();

            // Create OleDbCommand object and select data from worksheet Sheet1
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);

            // Create new OleDbDataAdapter
            OleDbDataAdapter oleda = new OleDbDataAdapter();

            oleda.SelectCommand = cmd;

            // Create a DataSet which will hold the data extracted from the worksheet.
            DataSet ds = new DataSet();

            // Fill the DataSet from the data extracted from the worksheet.
            oleda.Fill(ds, "Employees");

            // Bind the data to the GridView
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch
        {
        }
        finally
        {
            // Close connection
            oledbConn.Close();
        }     

    }

All set!! Run the application and see the data getting displayed in the GridView. If you want to target the Excel 2007 sheet, just change xls to xlsx in the ConfigurationManager.ConnectionString. 

Please let me know in case of you have any query in this article.






Saturday, May 7, 2011

How Insert data in Database in PHP

Hello Friends,
            In previous two blog we studied how to create database and how to connect with that database in PHP MySql. Now in this blog we are going to learn something very important for any site and that is How to enter or store the data in the database in PHP. In very simple word fill the registration form and click on the submit button  and data is stored in the database. So in this blog we are going to do the same thing. So let's start.


To perform this task we have to follow the following steps and you will get it very easily.
1. Fetch the data from the previous page using "name" property of input tag.
2. Write the query for insert the data in the database(simple insert query).
3. Execute(Run) that query.


That's it.


Let describe each step in detail. As I said earlier we will use the "StudentMaster" as 'our database and "StudentInfo" as our table of database.First of I tell you the fields (Columns ) of the table. ID(auto increment),FName,LName,PhoneNumber,EmailId,Password.


1. Fetch the data from the previous page using "name" property of input tag.
Let me show what is meaning of name property.
For example in previous page you have written "input ytpe="text name="FName"" then you have to fetch the value using the name propery i.e.FName.


You can fetch the value using GET,POST and REQUEST.If you are passing value using GET, you can fetch using GET and REQUEST. Same as you are passing value using POST,you can fetch using POST and REQUEST. So every time we will use REQUEST to fetch value irrespective of which method we used to pass the value. To fetch value following is the syntax.
$variablename=$_REQUEST/GET/POST['name property'];


So here to fetch the value of FName 
$fname=$_REQUEST['FName'];
fetch the value of ecach and every input as shown below:
$lname=$_REQUEST['LName'];
$phone=$_REQUEST['PNO'];
$email=$_REQUEST['EmailId'];
$pass=$_REQUEST['Pass'];


2. Write the query for insert the data in the database(simple insert query).
Now we have all the value to insert in the database. All the value we have stored in the respective variable name. We will use those variable. 
Simple insert query looks like :
insert into tblname(columns name) values ('values');
So in our example
$query="insert into StudentInfo (FName,LName,PhoneNumber,EmailId,Password) values ('$fname','$lname',$phone,'$email','$pass')";
Where $query is variable to store the query.


3.Execute(Run) the query.
We created the insert query in second step and we will run in this step.
To run the query we have MySql inbuilt function mysql_query(query)
So the final statement will be
mysql_query($query) or die ( mysql_error());
Where $query is our query created in step  and die I explained in previous blog.


So the final code is 

$fname=$_REQUEST['FName'];
$lname=$_REQUEST['LName'];
$phone=$_REQUEST['PNO'];
$email=$_REQUEST['EmailId'];
$pass=$_REQUEST['Pass'];

$query="insert into StudentInfo (FName,LName,PhoneNumber,EmailId,Password) values ('$fname','$lname',$phone,'$email','$pass')";

mysql_query($query) or die (mysql_error());

So please try this code and leave the comment if you like or If you have any doubts.
I'll wait for your response.

Sunday, May 1, 2011

How To Connect with database in PHP

Hello Friends,
                In previous blog we studied how to create the database in mysql for PHP.In this blog we'll see how to connect with the database in PHP means how to make a connection with our database using PHP.


Simple step to follow for inserting the data in database using PHP.
1.Create A connection with your Database.
2.Fetch the value from the Form using the name property of input.
3.Create the query for insert.
4.Execute(Run) the query.


In this whole blog,we'll use the "StudentMaster" as database and "StudentInfo" as table.And mind the whatever starts with $ sign is variable for temporary use.


So let's start with the first step.


1.Create A Connection With Your Database.
    In this step there are two steps.
    A. Create the connection with MySql server.
           For that there is code of only on line and that is.
                      $con=mysql_connect("localhost","root","");
            Here $con is variable.We are storing this connection in this variable for further use.
            --"mysql_connect" is mysql function for making connection with MySql server.
            --"localhost" is that where you are running your application.
            --If you are running in your system itself,it will always localhost.
            --"root" is user name.By default when you install the wamp server one user is creates that is root.
            --"" is the password for "root" user. By default is "";
            --Now we have connection with MySql server.
    
      B.Select your database from MySql server and make connection.
            For that the code is as follows.
                      $db=mysql_select_db("StudentMaster",$con) or die ( mysql_error());
            Here as I explained above $db is just a variable to store the value.
            --"mysql_select_db" is MySql is a function for selecting our database from MySql server.
            --"StudentMaster" is our database name.Type your database name whatever it is.
            --$con is our connection with MySql server as explained above.
            --or is the "or" operator means either left side or right side will run.
            --It means that either "mysql_select_db" will run or "mysql_error()" will run.
            --If "mysql_select_db" fails to run then "mysql_error()" (inbuilt error function of MySql) will run and  tell you the exact error what it is.

Whole code looks like
          
         $con=mysql_connect("localhost","root","");
       $db=mysql_select_db("StudentMaster",$con) or die (mysql_error());
           

------->How we are connected with the database and ready to use.In next blog we'll learn how to insert data in the database.
------->In this blog if you have any problem or you face any problem while connecting with database let me know.
------->Please leave a comment if it is useful to you.


------->We'll meet soon again.