我使用以下脚本并收到以下错误:
无法创建OLE DB提供程序的实例 " Microsoft.ACE.OLEDB.12.0"对于链接服务器"(null)"。
EXEC SP_CONFIGURE 'show advanced options', 1;
GO
RECONFIGURE;
EXEC SP_CONFIGURE 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=c:\CSV\testing.xlsx;',
'SELECT * FROM [Sheet1$]')
select top 10 * from Emp2
我该如何解决这个问题?我需要将数据导出到 UNC路径中的Excel文件。请指导我如何实现它。
我再次尝试下面的脚本,但这次我得到了一个不同的错误:
无法创建OLE DB提供程序的实例" Microsoft.Jet.OLEDB.4.0" 对于链接服务器"(null)"。
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\CSV\testing.xlsx;','SELECT ID,Name FROM [Sheet1$]')
select top 10 * from Emp2
请指导我如何将数据导出到将在UNC路径中生成的Excel文件。
答案 0 :(得分:1)
以下是一些值得尝试的事情。
从SQL Server表
将数据导出到现有的EXCEL文件insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
如果您不想提前创建EXCEL文件并想要将数据导出到该文件,请使用
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
要使用标题(列名称)将数据导出到新的EXCEL文件,请创建以下过程
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
所有细节都在这里......