我組合的程式碼, 沒測試過, 應該稍加修改與Debug即可...
<pre class="c" name="code">//宣告SQL Server連線字串
Dim con As New SqlConnection
Dim cmd As New SqlCommand
//宣告輸出TXT檔名
Dim FILE_NAME As String = "C:\Users\Owner\Documents\EmployeeList.txt"
//開啟檔案I/O
Dim objWriter As New System.IO.StreamWriter( FILE_NAME )
//連線SQL Server開始抓資料
Try
con.ConnectionString = "Server=(local)\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT EmployeeID, FirstName, LastName FROM Employee ORDER BY EmployeeID"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
//把資料寫入TXT檔, 寫入格式如何, 就自行修改一下囉...
objWriter.WriteLine( ldr.Item(0) & ", " & ldr.Item(1) & ", " & ldr.Item(2))
Next
End While
objWriter.Close()
Catch ex As Exception
MessageBox.Show("Error while retrieving records on Employee table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
1.你要先從SQL Server抓資料, 用ADO.NET或LINQ
2.你的VB.NET是寫成ASP.NET還是Windows From, 前者要輸出HTTP檔頭通知瀏覽器另存新檔, 後者要開對話框給User選存檔位置與檔名
用C#寫過, 但是之前硬碟毀了
不然就可以轉成 VB.NET 給你
所以死心吧
<pre class="c" name="code">
Dim TextFileConn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\;Extended Properties=Text;HDR=NO;")
TextFileConn.Open()
Dim TextFileCmd As New System.Data.OleDb.OleDbCommand("SELECT * INTO [Employee#txt] FROM [Employee] IN '' [ODBC;Driver={SQL Server};Server=(local);Database=Northwind;Trusted_Connection=yes];", TextFileConn)
TextFileCmd.ExecuteNonQuery()
TextFileConn.Close()