使用vb.net中的日期列将数据从sql server数据库导出到excel
我想做一个程序,将查询我的数据在sql server和导出到excel,我有2 txtbox在我的形式。txtFrom_日期和TXTO_日期,1个btnGenerateReport按钮。用户将在TXT框中输入开始日期和截止日期,单击“生成”时,将自动将指定日期的数据导出到excel 以下是我在报告表中的全部代码: 当我运行我的程序并输入txtFrom_Date 2018-02-21和txtTo_Date 2018-02-21时,我收到一条错误消息“在'2018'附近的语法不正确”。但当我检查我的数据库时,格式就是这样。 请帮我解决这个问题谢谢使用vb.net中的日期列将数据从sql server数据库导出到excel,vb.net,Vb.net,我想做一个程序,将查询我的数据在sql server和导出到excel,我有2 txtbox在我的形式。txtFrom_日期和TXTO_日期,1个btnGenerateReport按钮。用户将在TXT框中输入开始日期和截止日期,单击“生成”时,将自动将指定日期的数据导出到excel 以下是我在报告表中的全部代码: 当我运行我的程序并输入txtFrom_Date 2018-02-21和txtTo_Date 2018-02-21时,我收到一条错误消息“在'2018'附近的语法不正确”。但当我检查我的
'NOTE before coding export excel function must add reference first in
project properties(microsoft excel 2012)
'References that we need
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO.Directory
Imports Microsoft.Office.Interop.Excel 'Before you add this reference
to your project,
' you need to install Microsoft Office and find last version of this
file.
Imports Microsoft.Office.Interop
Public Class Report
Dim dataAdapter As New SqlClient.SqlDataAdapter()
Dim dataSet As New DataSet
Dim command As New SqlClient.SqlCommand
Dim datatableMain As New System.Data.DataTable()
Dim connection As New SqlClient.SqlConnection("SERVER=L4SMTDB01\SMTDBS02;DATABASE=SMT_IT;user=sa;pwd=qwerty;")
Private Sub ReleaseObject(ByVal o As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
End While
Catch
Finally
o = Nothing
End Try
End Sub
Private Sub btnGenerateReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click
' command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update between " & DateTimePicker1.Value.Date.ToOADate() & " and " & DateTimePicker2.Value.Date.ToOADate() & "")
' command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update >= ''" & txtFromDate.Text & "'' and Last_Update <= ''" & txtToDate.Text & "''")
'Assign your connection string to connection object
command.Connection = connection
command.CommandType = CommandType.Text
'' 'You can use any command sel
command.CommandText = String.Format("Select * from ComponentCheckerSystem where Last_Update between ''" & txtFromDate.Text & "'' and ''" & txtToDate.Text & "''")
dataAdapter.SelectCommand = command
connection.Close()
Dim f As FolderBrowserDialog = New FolderBrowserDialog
Try
If f.ShowDialog() = DialogResult.OK Then
'This section help you if your language is not English.
System.Threading.Thread.CurrentThread.CurrentCulture = _
System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
'Fill data to datatable
connection.Open()
dataAdapter.Fill(datatableMain)
connection.Close()
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
'Export the rows to excel file
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
'Set final path
Dim fileName As String = "\Summary of Operator Scan Wrong Items" + ".xls" 'just set the file Name
Dim finalPath = f.SelectedPath + fileName
txtPath.Text = finalPath
oSheet.Columns.AutoFit()
'Save file in final path
oBook.SaveAs(finalPath, XlFileFormat.xlWorkbookNormal, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
'Release the objects
ReleaseObject(oSheet)
oBook.Close(False, Type.Missing, Type.Missing)
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
'Some time Office application does not quit after automation:
'so i am calling GC.Collect method.
GC.Collect()
MessageBox.Show("Export done successfully!")
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
End Try
End Sub
Private Sub Report_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.CustomFormat = "YYYY-MMMM-DD"
DateTimePicker2.CustomFormat = "YYYY-MMMM-DD"
End Sub
”注意:在编码之前,导出excel函数必须先在中添加引用
项目属性(microsoft excel 2012)
“我们需要的参考资料
导入System.Data.SqlClient
导入系统数据
导入System.IO.Directory
在添加此引用之前导入Microsoft.Office.Interop.Excel
为了你的项目,
'您需要安装Microsoft Office并查找此版本的最新版本
文件
导入Microsoft.Office.Interop
公开课报告
Dim dataAdapter作为新的SqlClient.SqlDataAdapter()
将数据集设置为新数据集
Dim命令作为新的SqlClient.SqlCommand
Dim datatableMain作为新的System.Data.DataTable()
将连接作为新的SqlClient.SqlConnection(“SERVER=L4SMTDB01\SMTDBS02;DATABASE=SMT_IT;user=sa;pwd=qwerty;”)进行Dim连接
私有子释放对象(ByVal o作为对象)
尝试
While(System.Runtime.InteropServices.Marshal.ReleaseComObject(o)>0)
结束时
接住
最后
o=没有
结束尝试
端接头
私有子btnGenerateReport\u单击(ByVal发送方作为System.Object,ByVal e作为System.EventArgs)处理btnGenerateReport。单击
'command.CommandText=String.Format(“从ComponentCheckerSystem中选择*,在“&DateTimePicker1.Value.Date.ToOADate()&”和“&DateTimePicker2.Value.Date.ToOADate()&”之间最后一次更新)
'command.CommandText=String.Format(“从ComponentCheckerSystem中选择*,其中上次更新>=''”&txtFromDate.Text&““”和上次更新永远不要相信用户将在文本框中输入的内容。这可能对您的数据库非常有害。请学习使用参数。这将保护您的数据库并为您保存SQL字符串。请在表单中添加2个DateTimePicker
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "Select * from ComponentCheckerSystem where Last_Update between @FromDate AND @ToDate;"
command.Parameters.Add("@FromDate", SqlDbType.Date).Value = DateTimePicker1.Value.Date
command.Parameters.Add("@ToDate", SqlDbType.Date).Value = DateTimePicker2.Value.Date
这个怎么样
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Orders"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
End Class
您正在使用两个单引号表示日期。因此,请尝试使用'&txtFromDate.Text&“
而不是'&txtFromDate.Text&”
(也用于其他日期)。谢谢,现在它可以工作了SS…向你致敬!谢谢你的建议,现在我使用了参数。很抱歉,我不熟悉这一点。再次感谢。你能帮我回答我的新问题吗。@Mary为什么一些答案的左边没有复选标记?我想修改我的代码,使其自动保存在D:\work中,这样我就不会在保存文件时手动选择路径将自动重命名为data01、data02、data03,以便我不会删除现有文件。请将您的新问题作为新问题发布。这样,其他搜索答案的用户将得到帮助。