Reading Microsoft Excel data in ASP.Net

Reading Microsoft Excel sheet is quite simple in ASP.net. There are many ways to do CSV file reading in .Net. In this article I�m going to show an example which will get the data from excel sheet and display them in a Data GridView control.

First create a front-end design using your IDE.

Default.aspx



Code:
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Read Excel Sheet</title>
</head>
<body>
    <form id="form1" runat="server">
     <div>
         <asp:GridView ID="GridView1" runat="server">
         </asp:GridView>         
     </div>
    </form>
</body>
</html>


Now we will add code for pulling the excel data to grid.

Following are the steps involved in pulling Excel sheet.


  1. Open a connection
  2. Create a command object
  3. Create an OleDBDatareader object
  4. Execute the command object executereader and assign the data to OldDBdatareader object


Default.aspx.vb


Code:
Imports System.Data
Imports System.Data.OleDb

Partial Class _Default
    Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   

Dim sConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;"""

     Dim oConn As New OleDbConnection(sConn)
     oConn.Open()  ' open the connection here

     Dim oComm As New OleDbCommand("Select * From [Sheet1$]", oConn)

     ' Execute reader
     Dim oDataReader As OleDbDataReader
     oDataReader = oComm.ExecuteReader()
     ' Bind the data on to Grid
     GridView1.DataSource = oDataReader
     GridView1.DataBind()


End Sub
End Class

In Case if you need to loop through the data, you can try something like this.

Code:

While oDataReader.Read
      ' F1 is first colum if you havent added one
      Response.Write(oDataReader("F1").ToString & "<br />")         
End While



This will get you all the excel data to Gridview control. Another method to pull the excel data is using the OleDBDataadaptor and which is straight forward as well.

I hope this article will help you in someway. Please post your feed back if you have any.

Thanks

Commentaires

Posts les plus consultés de ce blog

XAJAX with PHP – The future of web development

XAJAX with PHP – The future of web development

Database connection pooling in ADO.Net