Reading Excel (.xls) Files with ADO.NET...

Reading Excel (.xls) Files with ADO.NET...

With a little preparation on the Excel side and very little work on the ADO.NET side you can connect to and read Excel workbooks just as though they were database tables.


By: John Kilgo Date: May 28, 2003 Download the code. Printer Friendly Version

Since Excel has an OleDB provider, we can use ADO.NET's OleDb functionality to connect to Excel. It does take a little preparation on the Excel side however. You might think that since Excel has rows and columns we might be able to use that and refer to A1 and B3, etc. We can't (as far as I know). We must resort to another method. Excel does provide for something called a "Named Range" which we can make use of. This Named Range becomes the equivalent of a table name if we were dealing with a real database. We must also use Excel's first row as column headings. In my example spreasheet that can be downloaded, the first row contains LastName | FirstName | Address | City | State. Additional rows contain the actual data.

To create the Named Range select (highlight) the cells you want in your "table". Then, from the menu, choose Insert | Name | Define. In the upper left corner of the resulting dialog box, type a name for your range. This will become the "table name" you will use in your SQL SELECT statement. The name (full path) of the spreadsheet will be the Data Source in your connection string as you will see in the code to follow. If you download the files and open up the spreadsheet we have included, then select all of the cells with data in them you will see "Addresses" at the left of the formula bar in Excel. Addresses is the name I gave my Named Range.

You must do the two things above (Named Range and a first row of column names) for this method to work. The rest is easy. Let's look at the code. First the .aspx page (ExcelSelect.aspx). There is nothing fancy about it. Just two label controls and two DataGrids. The two Labels are there to display the SQL SELECT statements for each DataGrid. I used two SELECT statements and two grids just to show that we can deal with the (properly setup) spreadsheet just as we would a database table.

<%@ Page Language="vb" AutoEventWireup="False" Src="ExcelSelect.aspx.vb" Inherits="ExcelSelect"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>ExcelSelect</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Label ID="lblSql1" Runat="server" />
<asp:DataGrid ID="dtgAddresses1" Runat="server"
              HeaderStyle-BackColor="IndianRed"
              HeaderStyle-ForeColor="White"
              HeaderStyle-Font-Name="Verdana"
              HeaderStyle-Font-Size="10"
              ItemStyle-BackColor="Gainsboro"
              ItemStyle-Font-Name="Verdana"
              ItemStyle-Font-Size="10"
              CellPadding="4"
              GridLines="Both" />
<p></p>
<asp:Label ID="lblSql2" Runat="server" />
<asp:DataGrid ID="dtgAddresses2" Runat="server"
              HeaderStyle-BackColor="IndianRed"
              HeaderStyle-ForeColor="White"
              HeaderStyle-Font-Name="Verdana"
              HeaderStyle-Font-Size="10"
              ItemStyle-BackColor="Gainsboro"
              ItemStyle-Font-Name="Verdana"
              ItemStyle-Font-Size="10"
              CellPadding="4"
              GridLines="Both" />
</form>
</body>
</html>

Now for the code-behind page ExcelSelect.aspx.vb. As you can see we are using the OleDb Jet provider. It is important to note that in the connection string the last parameter is "Extended Properties=Excel 8.0;". You MUST include this parameter. Really, the connection string is the only "tricky" part of this program. Once that is defined properly the rest is just executing a reader and binding the grid in the usual fashion. I set the label text in code just to save some typing. You wouldn't want that in there in a real application. Otherwise, the code pretty much speaks for itself.

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class ExcelSelect
  Inherits System.Web.UI.Page

  Protected dtgAddresses1 As System.Web.UI.WebControls.DataGrid
  Protected dtgAddresses2 As System.Web.UI.WebControls.DataGrid
  Protected lblSql1 As System.Web.UI.WebControls.Label
  Protected lblSql2 As System.Web.UI.WebControls.Label

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim strConn As String = "Provider=Microsoft.Jet.OleDb.4.0;" _
                          & "data source=f:/inetpub/wwwroot/dotnetjohn/NameAndAddress.xls;" _
                          & "Extended Properties=Excel 8.0;"
    'First DataGrid
    Dim objConn As New OleDbConnection(strConn)
    Dim strSql As String = "Select LastName, FirstName, Address, City, State From Addresses"
    lblSql1.Text = strSql
    Dim objCmd As New OleDbCommand(strSql, objConn)
    Try
      objConn.Open()
      dtgAddresses1.DataSource = objCmd.ExecuteReader()
      dtgAddresses1.DataBind()
    Catch exc As Exception
      Response.Write(exc.ToString())
    Finally
      objConn.Dispose()
    End Try
    'Second DataGrid
    objConn = New OleDbConnection(strConn)
    strSql = "Select * From Addresses Where State='CA'"
    lblSql2.Text = strSql
    objCmd = New OleDbCommand(strSql, objConn)
    Try
      objConn.Open()
      dtgAddresses2.DataSource = objCmd.ExecuteReader()
      dtgAddresses2.DataBind()
    Catch exc As Exception
      Response.Write(exc.ToString())
    Finally
      objConn.Dispose()
    End Try
  End Sub

End Class

Well there you have it. You can read from Excel in .Net. There are some practical problems obviously. Having to set the Named Ranges is an issue as well as having the first row of column headers. Also, you will receive an error if a user has the workbook open in write mode. But if you are desperate and really need to read Excel spreadsheets, this is a way to do it and have it look professionally done.

You may run the program here.
You may download the code here. Please remember that you will have to change the path in the connection string to wherever you place NameAndAddress.xls on your machine.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值