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

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航