SQL Server 2012 table data export to excel file

222 Views Asked by At

I would like to export data from a SQL Server stored procedure to an Excel file. How can I achieve that?

I test like that:

insert into OPENROWSET(
   'Microsoft.ACE.OLEDB.12.0', 
   'Excel 8.0;Database=D:\test.xlsx;;HDR=YES', 
   'SELECT EmpID FROM [Sheet1$]')
select * from tb1

but it returns an error:

Column name or number of supplied values does not match table definition.

I think it's because Excel doesn't have columns right? But there's no way to pre-write columns before exporting to Excel, and SQL Server can't create Excel by itself ...

I also tried with bcp:

bcp "SELECT * FROM mydb.tb1" queryout 'D:\test.xlsx' -t, -c -S . -d DESKTOP-D3PCUR7 -T

It returns error:

Incorrect syntax near 'queryout'.

How can I export table to Excel easily in SQL Server?

0

There are 0 best solutions below