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?

Share:
53,505
JohnIdol
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, 2020

Comments

  • JohnIdol
    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
    ZygD almost 15 years
    Ah I get you. No, you can't manipulate Excel that way in T-SQL. Perhaps a CLR stored proc?
  • JohnIdol
    JohnIdol almost 15 years
    never worked with CLR SPs - but I guess it's easy enough - any good sample to get me going?
  • ZygD
    ZygD almost 15 years
    Sorry... not used them. The "SQLCLR" tag has 31 related questions.
  • ZygD
    ZygD almost 15 years
    I'll clarify.. our corporate build from DB engineering says no
  • Sunil Acharya
    Sunil Acharya over 5 years
    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.