24

I am trying to read data from an Excel sheet (.xlsx file) into a table in SQL Server 2008. I want this to be run everyday as a batch job and hence want to write SQL code in a stored procedure to do so.

Could someone help me? I have admin rights.

~TIA

aaryan
  • 277
  • 1
  • 3
  • 9

6 Answers6

32

This should do...

SELECT *
FROM OPENROWSET(
    'Microsoft.ACE.OLEDB.12.0',
    'Excel 8.0;HDR=NO;Database=T:\temp\Test.xlsx',
    'select * from [sheet1$]')

But we aware, sometimes this just wont work. I had this working for local admins only.

There is a way to do this using SSIS as well.

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
kiri
  • 336
  • 2
  • 3
  • 2
    This link maybe useful: https://social.technet.microsoft.com/wiki/contents/articles/24236.importing-an-excel-spreadsheet-into-a-sql-server-database.aspx – QMaster Feb 18 '17 at 17:38
  • There is an important note regarding `OPENROWSET` at [docs](https://learn.microsoft.com/en-us/sql/relational-databases/import-export/import-data-from-excel-to-sql?view=sql-server-2017#openrowset): The ACE provider (formerly the Jet provider) that connects to Excel data sources is intended for interactive client-side use. If you use the ACE provider on the server, especially in automated processes or processes running in parallel, you may see unexpected results. – Janis Veinbergs Mar 07 '19 at 08:40
5

To, Import/Export data To/From Excel (.xls) need Microsoft.Jet.OLEDB.4.0 and for Excel 2007 (.xlsx) need 2007 Office System Driver: Data Connectivity Components. You can download from HERE

Import data from Excel to new SQL Server table Excel 2003 (.Xls) file:

select * into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')

Excel 2007 (.Xlsx) file:

Select * into SQLServerTable FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;HDR=YES', 'SELECT * FROM [Sheet1$]')

Import data from Excel to existing SQL Server table Excel 2003 (.Xls) file:

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')

Excel 2007 (.Xlsx) file:

INSERT INTO SQLServerTable select * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;HDR=YES', 'SELECT * FROM [Sheet1$]')
Jitendra Sawant
  • 648
  • 7
  • 14
  • In febr 2019 I downloaded the OLEDB drivers from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54920 . You need to have the same 32/64 bit version for AccessDatabaseEngine like the SQL server . AccessDatabaseEngine.exe is for 32bit AccessDatabaseEngine_x64.exe is for 64 bit. ... – mihai71 Feb 18 '19 at 09:32
  • I encountered some problems when installing when SQL was 64bit and Office 32 bit. If you already have Office installed, if your Office is different 32/64 bit than your SQL server, than you will receive an error about that. I used another computer which only had SQL server 64 bit installed, so I could install AccessDatabaseEngine_x64.exe and it worked. You don't need to have Office installed in order to be able to import Excel file in Sql Server. You only need to install AccessDatabaseEngine . HTH – mihai71 Feb 18 '19 at 09:33
1

Borrow from GridWizard https://gridwizard.wordpress.com/2014/12/23/tsql-utility-to-read-csv-and-excel-files/

/*
Usage:
exec sp_ReadExcelFile ‘C:\tmp’, ‘EmpData’, ‘EmpData.xls’, ‘[Sheet1$]’, ‘Col1,Col2,Col3,Col4,Col5′
*/
CREATE PROCEDURE sp_ReadExcelFile
(
@TargetFolder varchar(255), /* For example, ‘C:\tmp’ */
@TargetTable varchar(255), /* For example, ‘EmpData’ */
@ExcelFile varchar(255), /* For example, ‘EmpData.xls’ */
@ExcelSheet varchar(255), /* For example, ‘[Sheet1$]’ */
@ExcelFields varchar(8000) /* Comma separate list, for example: ‘Col1,Col2,Col3,Col4,Col5′ */
)
AS
BEGIN
declare @SqlStmt nvarchar(max)
declare @FirstColumn nvarchar(255)

set @SqlStmt = ‘IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N”[dbo].[‘ + @TargetTable + ‘]”) AND type in (N”U”))’
set @SqlStmt = @SqlStmt + ‘ DROP TABLE ‘ + @TargetTable
PRINT @SqlStmt
exec sp_executesql @SqlStmt

select top 1 @FirstColumn=[part] from fn_SplitString(@ExcelFields, ‘,’)
print ‘FirstColumn: ‘ + @FirstColumn

set @SqlStmt = ‘SELECT ‘ + @ExcelFields + ‘ INTO ‘ + @TargetTable + ‘ FROM OPENROWSET(”Microsoft.ACE.OLEDB.12.0”,
”Excel 12.0;DATABASE=’ + @TargetFolder + ‘\’ + @ExcelFile + ‘;IMEX=1”, ”Select * from ‘ + @ExcelSheet + ”’)’
+ ‘WHERE NOT ‘ + @FirstColumn + ‘ IS NULL’
PRINT @SqlStmt
exec sp_executesql @SqlStmt
END
GO

/*
Taken from: http://stackoverflow.com/questions/697519/split-function-equivalent-in-t-sql
Usage: select top 1 part from fn_SplitString(‘aaa,bbb,ccc,ddd,eee’,’,’)
*/
CREATE FUNCTION [dbo].[fn_SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter
begin
set @iStart = 2
insert into @tParts
values( null )
end
else
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos – @iStart > 0
insert into @tParts
values ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString )
break
end
RETURN
END
GO
Jaye
  • 152
  • 4
0

Right click on the database -> Tasks -> Import Data... Go through the wizard.

Dave.Gugg
  • 6,561
  • 3
  • 24
  • 43
  • Sorry for not being clear.. I am looking at running this everyday as a batch job and hence want to write SQL code in a stored procedure. – aaryan Jun 11 '14 at 21:36
  • In that case, an SSIS job is the way to go. If you run through the import wizard, it will create an SSIS package that you can save off. Then just set up a SQL Agent job to run that SSIS package once a day. – Dave.Gugg Jun 12 '14 at 12:53
0

The easiest way is probably the Import/Export Wizard in SQL Server Management Studio. Here is one site that explains how: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

Jerrad
  • 5,240
  • 1
  • 18
  • 23
  • Sorry for not being clear.. I am looking at running this everyday as a batch job and hence want to write SQL code in a stored procedure. – aaryan Jun 11 '14 at 21:26
0

Just another quick alternative

If you don't need to import your Excel file programmatically using code you can do it very quickly manually using the menu in SQL Management Studio:

How to import an Excel file into SQL Server?

Community
  • 1
  • 1
Spyder
  • 3,784
  • 3
  • 26
  • 15