ADO - how to select column from xls file where two or more columns have the same name?

故事扮演 提交于 2020-01-02 06:23:11

问题


I have an excel file like this:

|   |    A   |    B    |    C    |   D    |
| 1 | Name 1 |  Name 2 |  Name 3 | Name 2 |
| 2 |  Data  |  Data   |  Data   | Data   |
| 3 |  Data  |  Data   |  Data   | Data   |

As you can see, headers of two columns have the same name - Name 2.

My question is, is it possible to tell the ADO engine from which column to select data?

Currently my select looks like this:

SELECT [Name 1], [Name 2] FROM [REPORT7_RAW$] WHERE [Name 1] IS NOT NULL

and ADO picks up the data from column which is listed under column B in excel. In other words it takes the first column which have the given name. Unfortunately I have two columns with the same name and I would like to pull out the data from column D. Is it possible?

I could not find any way to select column by its index rather the name.


回答1:


You will need to change your connection string so that data header names are not used. The normal connection string would look something like this:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties="Excel 12.0 Xml;HDR=YES";

You need to change the last bit, HDR=YES, to HDR=NO.

With that type of connection, the columns(fields) then become F1, F2, etc., where F1 = column A, F2 = column B, etc.

This is not ideal, since you are now essentially running the query based on the number of the column rather than the name, but with duplicate column names, this is the only way around that.

Per the comment from @barrowc: This format of the connection string will treat your column names as data. So depending on your query, you may need to include code to filter out the row that contains your column names.



来源:https://stackoverflow.com/questions/18360306/ado-how-to-select-column-from-xls-file-where-two-or-more-columns-have-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!