Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server stored procedure export to Excel workbook with multiple sheets

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?

like image 949
kelvinfix Avatar asked Jan 05 '12 09:01

kelvinfix


1 Answers

  1. Create an empty Excel file with the sheets in it you need (my example sales.xls with sheets "sheet1","sheet2")

  2. Copy empty file to desired location/name

  3. 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:\export\sales.xls;;HDR=YES', 
       'SELECT * FROM [Sheet1$]')
    select * from sales_part1
    
  4. Using 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:\export\sales.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:
SQL Server export to Excel with OPENROWSET
error on sql script with 'openrowset'

like image 90
Niranjan Singh Avatar answered Oct 04 '22 12:10

Niranjan Singh