使用vb.net中的Date列将数据导出到sql server数据库中的excel

问题描述 投票:-1回答:2

我想制作一个程序,在sql server中查询我的数据并导出到excel,我的表单中有2个txtbox。 txtFrom_Date和txtTo_Date,1 btnGenerateReport按钮。用户将在txtbox中输入开始日期和直到日期,当单击btnGenerate时,它将自动将数据导出到指定日期的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

结束班

vb.net
2个回答
1
投票

永远不要相信用户将放在文本框中的内容。这可能对您的数据库非常不利。学习使用参数。这将保护您的数据库并保存格式化SQL字符串的麻烦。在表单中添加2个DateTimePickers。

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

0
投票

这个怎么样?

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
© www.soinside.com 2019 - 2024. All rights reserved.