Excel adapter for ADO. net

Source: Internet
Author: User
From http://www.codeproject.com/KB/grid/ExcelAdapter.aspx

On the recent project I worked on, I had a requirement to load data from an Excel spreadsheet to a database on a regular basis. my goal was to load the data from Excel to a ADO. net dataset and run my business rules. I couldn't find any articles addressing this problem and so I decided to write one.

There are two projects added in the source code package.

    • ExceladoadapterBuilds the library,Exceladoadapter. dll.
    • ExceladaptertestIs a test windows form application.

In addition, you need to add the following references.

    • Microsoft Excel 11.0 Object Library
    • Microsoft Office 11.0 Object Library

All sample codes in this articles are in C #.

This component uses Microsoft Office 2003 InterOP assemblies to handle the Excel source and the code is written in C #. The individual worksheets on the Excel Workbook will be loaded into separateDatatableS on the dataset. I have a workbook, purchaseorder, with 5 worksheets; MERs, orders, orderdetails, shippers and products. the load process will create a dataset with 5 tables. the name of the dataset will be set to the name of the Excel Workbook, in this example purchaseorder. theDatatableNames will be the name of the worksheets.

 

 

 

Background

For more information on the Office 2003 InterOP assemblies, refer msdn reference.

Using the code

The most important thing to remember when working with Excel is to get a valid range of cells on the worksheet to work with. We certainly don't want all the empty cells to get loaded intoDatatableS. The logic that I used to get the valid range is depicted below:

Collapse | Copy code
 ///   <Summary />  ///  Gets the valid range of cells to work.  ///  </Summary />  ///     ///   <Returns />Excel range</Returns /> Private Microsoft. Office. InterOP. Excel. Range getvalidrange (worksheet sheet ){ String Downaddress = "  " ; String Rightaddress = "  " ; Long Indexold = 0 ; Long Index = 0 ; Microsoft. Office. InterOP. Excel. Range startrange; Microsoft. Office. InterOP. Excel. Range rightrange; Microsoft. Office. InterOP. Excel. Range downrange;Try { //  Get a range to work Startrange = sheet. get_range ( "  A1" , Missing. value ); //  Get the end of values to the right          //  (Will stop at the first empty cell) Rightrange = startrange. get_end (xldirection. xltoright ); /* Get_end method scans the sheet in the direction specified * until it finds an empty cell and returns the previous cell. * We need to scan all the columns and find the column with * the highest number of rows (row count ). * Then use the prefix character on the right cell and the * row count to determine the address for the valid range. */          While ( True ) {Downrange = rightrange. get_end (xldirection. xldown); downaddress = downrange. get_address ( False , False , Eferencestyle. xla1, type. Missing, type. Missing); Index = getindex (downaddress ); If (Index> = 65536 ) Index = 0 ; If (Index> indexold) indexold = index; If (Rightrange. Column = 1 ) Break ; Rightrange = rightrange. Previous;} rightrange = startrange. get_end (xldirection. xltoright); rightaddress = rightrange. get_address ( False , False , Referencestyle. xla1, type. Missing, type. Missing ); Return Sheet. get_range ("  A1" , Getprefix (rightaddress) + indexold );} Catch (Exception ){ Throw ;} Finally {Startrange = Null ; Rightrange = Null ; Downrange = Null ;}}

Startrange = sheet. get_range ("A1", Missing. value );Sets the starting cellA1Which is the top left cell on the Excel worksheet.Get_endMethod onRangeObject scans the sheet in the direction specified until it finds a empty cell and returns the previous cell. But a blank cell can also hold valid values as shown below.

 

To avoid this problem, you need to check all the columns and find the column with the highest number of rows and use that as the boundary for the valid range. but still if all the cells in the row are blank,Get_endMethod will not find any rows after that row.

Once after a valid range is found, we can create a two dimen1_array and load the array toDatatable. See the code segment below.

Collapse | Copy code
 ///   <Summary />  ///  Loads the data table.  ///   </Summary />  ///    ///   <Returns /></Returns />  Private System. Data. datatable loaddatatable (worksheet sheet ){ Object [] Columnvalues; system. Data. datatable dt = New System. Data. datatable (); DT. tablename = sheet. Name; Microsoft. Office. InterOP. Excel. Range range; Try {Range = getvalidrange (sheet ); Object [,] Values = ( Object [,]) Range. value2; columnvalues = New   Object [Values. getlength ( 1 )]; For ( Int I = 1 ; I <= values. getlength ( 0 ); I ++ ){If (I = 1 & _ Firstrowheader ){ For ( Int J = 1 ; J <= values. getlength ( 1 ); J ++ ){ Object Value = values [I, j]; If (Value! = Null ) Dt. Columns. Add (value. tostring ()); Else DT. Columns. Add ( " " );}} Else { For ( Int J = 1 ; J <= values. getlength ( 1 ); J ++ ){ Object Value = values [I, j]; If (Value! = Null ) {Columnvalues [J- 1 ] = Value. tostring ();}Else {Columnvalues [J- 1 ] = "  " ;}} DT. Rows. Add (columnvalues );}} Return DT ;} Catch (Exception ){ Throw ;} Finally {Range = Null ;}}

I hope you will find the code useful. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.