编程语言

img hiyaolee

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

发表于2004/10/6 18:26:00  803人阅读

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

相关文章推荐

img
取 消
img