Reading Excel (.xls) Files with add ...
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 name 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, The Select All of the Cells with Data 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 = "inherits =" excelselect "%>