SQL Server export to Excel with OPENROWSET
Asked Answered
C

3

4

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?

Cymophane answered 26/5, 2009 at 10:11 Comment(1)
Oh lucky man. I've been already spending 2 hours trying to run this and getting all kind of errors. (using 2008SP2)Arron
V
7

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

Vries answered 26/5, 2009 at 11:25 Comment(6)
this is good - but I'd still have to put the template there in the first place so I cannot come up with names in the SQL, I'd have to programmatically create the spreadsheet first.Cymophane
Ah I get you. No, you can't manipulate Excel that way in T-SQL. Perhaps a CLR stored proc?Vries
never worked with CLR SPs - but I guess it's easy enough - any good sample to get me going?Cymophane
Sorry... not used them. The "SQLCLR" tag has 31 related questions.Vries
I'll clarify.. our corporate build from DB engineering says noVries
I'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.Incapacity
S
1

Couldn't you make a copy of your template first, then pass the copy's filename into OPENROWSET?

Snub answered 28/11, 2009 at 0:59 Comment(0)
G
0

You can use a template in one location and the data file in other location. When you run the script , it will delete the old file and generates a new data file.

 EXEC xp_cmdshell 'del D:\template.xls'
 EXEC xp_cmdshell 'copy C:\template.xls D:\template.xls'

 INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
 'Excel 8.0;Database=D:\template.xls;', 
 'SELECT * FROM [SheetName$]') 
  SELECT * FROM myTable
Gourd answered 29/7, 2020 at 3:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.