[英]Export Sql Server data to formatted Excel
Is there a way to export some data from SQL Server to previously formatted Excel?有没有办法将一些数据从 SQL 服务器导出到以前格式化的 Excel? Eg user has formatted Excel for his own report and want to have data from Sql (rows) in this report?
例如,用户已为自己的报告格式化 Excel 并希望在此报告中获得来自 Sql(行)的数据? How this can be achieved?
如何做到这一点? Thanks!
谢谢!
There are so many ways to move data between SQL Server and Excel.在 SQL 服务器和 Excel 之间移动数据的方法有很多。
' set a reference to Microsoft ActiveX Data Objects 2.8 Library'
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "your_server_name" ' Enter your server name here
Database_Name = "NORTHWND" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [Customers]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
For iCols = 0 To rs.Fields.Count - 1
Worksheets("Sheet1").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
With Worksheets("sheet1").Range("a2:z500") ' Enter your sheet name and range here
'.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
You can use Microsoft SQL Server Management Studio to generate Excel by using Export Wizard.. An excellent article to get start.您可以使用 Microsoft SQL Server Management Studio 通过导出向导生成 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.