I have a script that does various things and the end result is one large table. I was wondering how I could export this final table to a new Excel file (with column headers as well).
I would need to do this within the script.
This question is related to
sql-server-2008
tsql
excel
Use PowerShell:
$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"
# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath
In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.
Source: Stackoverflow.com