分享
 
 
 

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有