SQL Server export to Excel with OPENROWSET
53,505
Solution 1
You'd have to use dynamic SQL. OPENROWSET
etc only allows literals as parameters.
DECLARE @myfile varchar(800)
SET @myfile = 'C:\template.xls'
EXEC ('
insert into OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',
''Excel 8.0;Database=' + @myfile + ';'',
''SELECT * FROM [SheetName$]'')
select * from myTable
')
Remember: the path is relative to where SQL Server is running
Solution 2
Couldn't you make a copy of your template first, then pass the copy's filename into OPENROWSET?
Author by
JohnIdol
The world will be mine but then I'll be killed by my own AI. Or by a giant simulated C. elegans out of the OpenWorm project. You can follow me on twitter.
Updated on July 29, 2020Comments
-
JohnIdol almost 4 years
I am successfully exporting to excel with the following statement:
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\template.xls;', 'SELECT * FROM [SheetName$]') select * from myTable
Is there any standard way to use this template specifying a new name for the excel sheet so that the template never gets written to or do I have to come up with some work-around?
What's the best way to do this in people experience?
-
ZygD almost 15 yearsAh I get you. No, you can't manipulate Excel that way in T-SQL. Perhaps a CLR stored proc?
-
JohnIdol almost 15 yearsnever worked with CLR SPs - but I guess it's easy enough - any good sample to get me going?
-
ZygD almost 15 yearsSorry... not used them. The "SQLCLR" tag has 31 related questions.
-
ZygD almost 15 yearsI'll clarify.. our corporate build from DB engineering says no
-
Sunil Acharya over 5 yearsI'm following the same but getting this error "The OLE DB provider "Microsoft.Jet.OLEDB.12.0" has not been registered." I have tried to change the OLEDB version also.