openrowset for excel: can we skip several rows?

血红的双手。 提交于 2019-12-18 05:45:06

问题


I will use the following sql to read data from excel, but sometimes I need to skip first several rows. e.g the real data begins from line 5, so I need to skip the first 4 rows, is that doable?

 SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;HDR=YES;Database=c:\daniel\test.xls',
    'SELECT * FROM [sheet1$]');

回答1:


Use a range [sheet1$A5:Z] instead of the entire sheet [sheet1$]

SELECT *
FROM OPENROWSET(
    'Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;HDR=YES;Database=c:\daniel\test.xls',
    'SELECT * FROM [sheet1$A5:Z]'
);



回答2:


This will number the rows being obtained, with no specific order (as luck would have it):

SELECT *
FROM (
  SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;HDR=YES;Database=c:\daniel\test.xls',
    'SELECT * FROM [sheet1$]')
) s
WHERE rownum > 4;

You may want to specify some order, if you see fit, by changing the rownum definition like this:

ROW_NUMBER() OVER (ORDER BY specific_column_list) AS rownum


来源:https://stackoverflow.com/questions/4929217/openrowset-for-excel-can-we-skip-several-rows

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