【SQLserver】用OPENDATASOURCE函数将EXCEL数据写入SQLserver表中

使用T-SQL语句将excel表数据写入SQLserver的实现方式.

一、使用OPENDATASOURCE前需要确保该服务开启:

    exec sp_configure 'show advanced options',1
    reconfigure
    exec sp_configure 'Ad Hoc Distributed Queries',1
    reconfigure

    EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1

    EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1

二、相关操作语句

--SQLserver中查询EXCEL表中的数据

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
 
'Data Source=C:\test.xlsx;Extended Properties="Excel 8.0;HDR=YES;IMEX=1"')
 
...sheet$
 
--表格存放路径可以自定义,一般都是C盘.
--将excel数据插入到数据表,进行数据加工处理,注意查询出来的列和表列数需一致.
insert into test.dbo.test(字段名A,B,C,D) --必须和EXCEL列名一致.
SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
'Data Source=C:\Data\DDfiles\test.xlsx;Extended Properties="Excel 8.0;HDR=YES;IMEX=1"')
...[sheet$]  --表格文件里的表名

三、使用结束后关闭。


--使用完成后,关闭Ad Hoc Distributed Queries:
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure