kravits88 kravits88 - 7 months ago 15
SQL Question

Import multiple Excel files/sheets into SQL Table

I have about 100 xlsx files, all with 1-7 sheets each. Each file and sheet has the same columns as the table I want to import everything into.

I can use this successfully:

SELECT *
FROM OPENROWSET(
'Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\0.xlsx',
'SELECT * FROM [sheet1$]'
)


or

SELECT * FROM OPENDATASOURCE( 'Microsoft.ACE.OLEDB.12.0', 'Data Source="C:\0.xlsx";
Extended properties=Excel 8.0')...Sheet1$


But how can I import multiple sheets from a file?

Answer
  1. Create linked server for the Excel file
  2. Use sp_tables_ex to discover the tables that the provider returns (mostly this should be the worksheet names but it may depend on the provider implementation)

Linked Server

EXEC sp_addlinkedserver
    @server = 'ExcelServer1',
    @srvproduct = 'Excel',
    @provider = 'Microsoft.Jet.OLEDB.4.0',
    @datasrc = 'C:\Test\excel-sql-server.xls',
    @provstr = 'Excel 8.0;IMEX=1;HDR=YES;'

EXEC sp_dropserver
    @server = N'ExcelServer1',
    @droplogins='droplogins'