我已经看到了一些关于如何导出到.xlsx但是它们都需要DSN的示例。我需要一个DSNLess示例,说明如何将Sql Server 2008查询结果导出到.xlsx文件。
我如何连接到sql server并运行select查询
$server = "Server1"
$database = "database1"
$query = "SELECT * from master"
$filepath = "C:\projects\excel1.xls";
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.add()
$worksheetA = $workbook.Worksheets.Add()
$sheet1 = $workbook.worksheets.Item(1)
$sheet1.name = "Sheet1 - Test"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $query
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$dataTable = new-object "System.Data.DataTable"
$dataTable = $dataSet.Tables[0]
$x=1
$dataTable | FOREACH-OBJECT{
#Here is where the actual export to .xlsx would go
$x++}
$excel.ActiveWorkbook.SaveAs("$filepath ")
$excel.quit()
答案 0 :(得分:0)
您不需要DSN。您只需要格式正确的ConnectionString。
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
然后使用OleDbConnection / Command执行查询。
或者,导出为CSV,然后在Excel中转换为XLSX。