title: Export data from SQL Server query to excel
body: <p>I want to export data from a query to excel file. I know that there is a lot of questions like these one here, but no one is acceptable in my situation.</p>
  
  <p>For example, like this topic using OPENROWSET: <a href="https://stackoverflow.com/questions/9086880/t-sql-export-to-new-excel-file">T-SQL: Export to new Excel file</a> </p>
  
  <pre><code>insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
  'Excel 8.0;Database=D:\testing.xls;', 
  'SELECT * FROM [SheetName$]') select * from SQLServerTable
  </code></pre>
  
  <p>It only execute successfully when I create testing.xls myself, and also define exactly number of columns that will be export from my query in this excel file. Otherwise, an error occur: Column name or number of supplied values does not match table definition.</p>
  
  <p>I also try another solution here: <a href="http://weblogs.sqlteam.com/mladenp/archive/2006/07/25/10771.aspx" rel="nofollow noreferrer">http://weblogs.sqlteam.com/mladenp/archive/2006/07/25/10771.aspx</a> using Exec master..xp_cmdshell</p>
  
  <p>It is really work, but, I heard that xp_cmdshell is a big security threat for SQL Server. So, may be I shouldn't use it.</p>
  
  <p>Is there any other way I can try?</p>