简体   繁体   English

将 SQL 数据导出到 Excel - 最佳方法?

[英]Export SQL data to Excel - Best possible approach?

I am currently working on an automation which requires to export sql results to excel data.我目前正在研究需要将 sql 结果导出到 excel 数据的自动化。 I want to do this via SQL query.我想通过 SQL 查询来做到这一点。 Few options i know are as below, but before i start exploring these things.我知道的选项很少如下,但在我开始探索这些东西之前。 I would like to know the best possible approach .我想知道最好的方法。

PS - It would be really great if there is a way to dynamically create excel during query execution and export data in multiple excel sheets. PS - 如果有一种方法可以在查询执行期间动态创建 excel 并将数据导出到多个 excel 表中,那就太好了。

  1. OPENROWSET开路集
  2. bcp_cmd bcp_cmd

You can CREATE VIEW and utilize that view in Excel 2016 under its data connections through PowerQuery .您可以在Excel 2016通过PowerQuery CREATE VIEW并在其数据连接下使用该视图。 Views are preferred since they are managed independently in the server, and provide realtime data results without requiring a full query to be embedded in the Excel file.视图是首选,因为它们在服务器中独立管理,并提供实时数据结果,而无需在 Excel 文件中嵌入完整的查询。 The resulting set exists in the workbook as a refresh-able table.结果集作为可刷新表存在于工作簿中。 Results that need to be recorded should be done via new workbooks or UPDATE 's back to the server in a separate script.需要记录的结果应该通过新的工作簿或UPDATE在单独的脚本中返回到服务器来完成。

在此处输入图片说明

In the PowerQuery Editor, Home tab, click Advanced Editor .在 PowerQuery 编辑器的“主页”选项卡中,单击“ Advanced Editor The database connection string and call to the server is below.数据库连接字符串和对服务器的调用如下。 You can also dynamically pass parameters from an Excel table to the query utilizing a table in the Name Manager .您还可以使用Name Manager中的表将参数从 Excel 表动态传递到查询。

Excel tab, table name: tbl_Parameters

    A         B
1 StartDate  01/01/2020
2 EndDate    02/01/2020
let
   Source = Sql.Database("ServerName" , "Database", [Query="

DECLARE @Start_Date AS datetime
DECLARE @End_Date AS datetime

SET @Start_Date = '"&StartDate&"'
SET @End_Date = '"&EndDate&"'


SELECT * FROM uvw_product
WHERE item_sold_date BETWEEN
@Start_Date AND @End_Date

"])
in
   Source

A while back I cobbled this Powershell script together.不久前,我将这个 Powershell 脚本拼凑在一起。
It querys sql server data, saves as csv, formats it and saves as xls, then mails via smtp.它查询sql server数据,保存为csv,格式化并保存为xls,然后通过smtp发送邮件。
You can set up a windows scheduled task to automate it.您可以设置 Windows 计划任务以使其自动化。

There's also an import xls module for powershell.还有一个用于 powershell 的import xls 模块

Import-Module Sqlps -DisableNameChecking;

#execute mysql query as excel
$Server = "DB SERVER";
$Database = "DBNAME";

$Query = @"
*SELECT QUERY HERE*
"@
$a = Get-Date
#note: if you run get-location from ide, it will use the ide path instead of the script path 
$currentLocation = Split-Path -Parent $PSCommandPath
$FilePath = $currentLocation + "\CSVName.csv"
$SavePath = $currentLocation + "\XLSFileName" +$a.Day+ $a.Month + $a.Year + ".xls"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $Server; Database = $Database; User ID = DBUSERNAME; Password = PASSWORD";
$SqlConnection.Open()
$sqlcmd = $SqlConnection.CreateCommand()
$sqlcmd.Connection = $SqlConnection
$sqlcmd.CommandText = $Query


$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $sqlcmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv -notypeinformation $FilePath


$SqlConnection.Close()
#Invoke-Sqlcmd -Query $Query -ConnectionString $SqlConnection.ConnectionString | Export-Csv -notypeinformation $FilePath

#release memory function
function Release-Ref($ref){
    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

#format excel to display correct date
$objExcel = new-object -comobject excel.application  
$objWorkbook = $objExcel.Workbooks.open($FilePath)
$objWorksheet = $objWorkbook.Worksheets.Item(1) 
$objRange = $objWorksheet.UsedRange
[void] $objRange.EntireColumn.Autofit()
$objWorkbook.Saved = $True
$objExcel.DisplayAlerts = $False
$objWorkbook.SaveAs($SavePath,1)
$objExcel.Quit()

#release memory
Release-Ref($objWorksheet) 
Release-Ref($objWorkbook) 
Release-Ref($objExcel)

#create mail
$smtpServer = "SMTPSERVER"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$att = new-object Net.Mail.Attachment($SavePath)
$msg = new-object Net.Mail.MailMessage
$msg.Subject = "EMAIL SUBJECT"
$msg.From = "FROM EMAIL"
#$msg.To.Add("TO EMAIL 1")
$msg.To.Add("TO EMAIL 2")
$msg.Body = @"
Hi,

MSG BODY HERE

Best Regards
"@
$msg.Attachments.Add($att)

$smtp.Send($msg)
$att.Dispose()

Download and install the 64-bit or 32-bit version of the driver, based on what you have installed.根据您安装的内容,下载并安装 64 位或 32 位版本的驱动程序。

https://www.microsoft.com/en-us/download/details.aspx?id=13255 https://www.microsoft.com/en-us/download/details.aspx?id=13255

Then, you should be able to run this.然后,您应该能够运行它。

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

Notice: this may not work if you have one 32-bit technology and one 64-bit technology.注意:如果您拥有一种 32 位技术和一种 64 位技术,这可能不起作用。 In this case, you may need to employ some kind of workaround.在这种情况下,您可能需要采用某种解决方法。

See this link for additional ideas of how to integrate SQL Server and Excel.有关如何集成 SQL Server 和 Excel 的其他想法,请参阅此链接。

https://solutioncenter.apexsql.com/how-to-import-and-export-sql-server-data-to-an-excel-file/ https://solutioncenter.apexsql.com/how-to-import-and-export-sql-server-data-to-an-excel-file/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM