Question posted 2012 · +5 upvotes
How can I export to an Excel workbook from a stored procedure to multiple sheets with few sql statements?
I am currently using the following statement:
EXEC proc_generate__excel 'db', 'temp',@filename, @SeqNo, @ext, @sqlorder
It will create three Excel workbooks, if there are three sql statement.
How can I export data from three sql statement to three sheets in one Excel workbook?
Accepted answer +6 upvotes
Create an empty Excel file with the sheets in it you need (my example sales.xls with sheets “sheet1″,”sheet2”)
Copy empty file to desired location/name
Using your select statement to get the desired information for sheet1; insert the data into the excel file:
insert into OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=d:exportsales.xls;;HDR=YES', 'SELECT * FROM [Sheet1$]') select * from sales_part1Using your select statement to get the desired information for sheet2; insert the data into the excel file:
insert into OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=d:exportsales.xls;;HDR=YES', 'SELECT * FROM [Sheet2$]') select * from sales_part2
Check these links for reference:
http://www.sqlservercentral.com/Forums/Topic487837-19-1.aspx
http://www.sqlservercentral.com/Forums/Topic660148-338-1.aspx
http://www.databasejournal.com/features/mssql/article.php/10894_3331881_1
Some SO threads:
SqlServer to Excel export with OPENROWSET
error on sql script with 'openrowset'
2 code variants in this answer
- Variant 1 — 5 lines, starts with
insert into OPENROWSET( - Variant 2 — 5 lines, starts with
insert into OPENROWSET(
External references cited (3)
- sqlservercentral.com — http://www.sqlservercentral.com/Forums/Topic487837-19-1.aspx
- databasejournal.com — http://www.databasejournal.com/features/mssql/article.php/10894_3331881_1
- stackoverflow.com — SqlServer to Excel export with OPENROWSET
Top excel Q&A (6)
- Shortcut to Apply a Formula to an Entire Column in Excel +335 (2011)
- How should I escape commas and speech marks in CSV files so they work in Excel? +136 (2012)
- Convert xlsx to csv in linux command line +96 (2012)
- How to create a link inside a cell using EPPlus +50 (2011)
- IF statement: how to leave cell blank if condition is false ("" does not work) +44 (2013)
- T-SQL: Export to new Excel file +44 (2012)
excel solutions on this site
.