December 3, 2009

SQL SERVER: How to Read Excel file by TSQL

Many times developers asked that, they want to import data from Excel file.

We can do this by many ways with SQL SERVER.

1. We can use SSIS package
2. Import/Export Wizard
3. T-SQL

Today, I am going to explain, How to import data from Excel file by TSQL.

To import Excel file by TSQL, we need to do following:

1. Put Excel file on server, means we need to put files on server, if we are accessing it from local.

2. Write following TSQL, to read data from excel file

SELECT Name, Email, Phone 
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\SQLYoga.xls', [SQL$])

ExcelFile

NOTE: Here, Excel file is on "C:\" named "SQLYoga.xls", and I am reading sheet "SQL" from this excel file

If you want to insert excel data into table,

INSERT INTO [Info]
SELECT Name, Email, Phone 
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test\SQLYoga.xls', [SQL$])

That's it.

4 comments:

  1. while running query i gave error
    Msg 15281, Level 16, State 1, Line 1
    SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online.

    ReplyDelete
  2. Hi,

    It means you need to allow this from server.

    You need to enable "Ad Hoc Distributed Queries" configuration to run this query.

    You can enable this deature by:

    sp_config 'Ad Hoc Distributed Queries',1
    reconfigure

    Thanks,

    Tejas

    ReplyDelete
  3. Can you only read a file that is stored on the c: drive of the local SQL Seerver? Is it possible to access an excel file that is located elsewhere on a network? How?

    ReplyDelete
  4. Hi Steve,

    We can read file from any location where SQL SERVER instance is running. e.g. If system has D drive then it can read like D:\SQLYoga.xls.

    About to read from Network location, SQL can read file from network location to. For that, please make sure that SQL SERVER account has an access to that network location. If SQL server has an access to that location, we can write it like this:

    SELECT Name, Email, Phone
    FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=\\Server2\SharedFolder\SQLYoga.xls', [SQL$])

    Thanks,
    Tejas
    SQLYoga.com

    ReplyDelete