I am using the below code, it is working as expected, but the issue with it is that if I have special characters like "öäõü" in sql query results, these will be not correctly displayed in excel.
For CSV -Encoding UTF8
will do the trick, but for excel, I tried to Google, but seems there is no easy solution to fix this.
$Server = "server"
$Database = "db"
$Query = "SELECT * FROM mytable"
$FilePath = "C:\OutputFile.csv"
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server |
Export-Csv $FilePath -NoTypeInformation -Encoding UTF8
$inputCSV = "C:\OutputFile.csv"
$outputXLSX = "C:\OutputFile.xlsx"
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.Worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.Add($TxtConnector, $worksheet.Range("A1"))
$query = $worksheet.QueryTables.Item($Connector.Name)
### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(3)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
$Workbook.SaveAs($outputXLSX, 51)
$excel.Quit()