通过验证将Excel导入datagridview

时间:2018-06-25 17:49:33

标签: excel vb.net visual-studio datagridview import

当前,我可以使用一个按钮将excel文件导入到datagridview中。我尝试了许多在网上找到的不同代码来导入,最后找到了一个稍有改动的可行代码。我遇到的最大问题是“读取” excel文件中单元格的内容,如果有某些我不希望执行的验证步骤,程序将不会导入文件。

例如,在第1列中,如果数字小于0,则应取消导入。

或另一个示例,如果一列(仅应为数字)的输入为字母,则应取消导入。

在其他语言中,我可以将其描述为简单的If语句,但是我是VB的新手。

如果有人可以引导我朝正确的方向前进,那将不胜感激

我使用的主页是; Importing Excel Data in Datagridview using VB.Net

我当前的代码;

    Dim dbconnect As OleDb.OleDbConnection
    Dim dta As OleDb.OleDbDataAdapter

    Dim dts As DataSet
    Dim excel As String
    Dim OpenFileDialog As New OpenFileDialog

    OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"

    If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then

        Dim file As New FileInfo(OpenFileDialog.FileName)
        Dim FileName As String = OpenFileDialog.FileName
        ' Dim selectedrowcount As Integer = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)

        excel = file.FullName
        dbconnect = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1'")
        dta = New OleDbDataAdapter("select * from [Feuil1$]", dbconnect)
        ' dta = New OleDbDataAdapter("select * from [Sheet1$]", dbconnect)

        dts = New DataSet

        dta.Fill(dts, "[Feuil1$]")

        ' dta.Fill(dts, "[Sheet1$]")
        DataGridView1.DataSource = dts
        DataGridView1.DataMember = "[Feuil1$]"
        dbconnect.Close()

        DataGridView1.DefaultCellStyle.Format = "N2"

                   DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

        '   MsgBox("Data has been imported")

    End If

End Sub

1 个答案:

答案 0 :(得分:0)

这是我评论中的一个基本示例。请注意,关闭命令已向上移动。

在这种情况下,仅当数据以您希望的方式显示时,数据才绑定到网格。

' Fill Data Set and Close Connection (I Moved the Close)
dts = New DataSet
dta.Fill(dts, "[Feuil1$]")
dbconnect.Close()

' Loop Through the Data And Make Sure Its Good
Dim dataSuccess as Boolean = True
Dim rowIndex as Integer = 0
For Each row as DataRow in dts.Tables(0).Rows

    If Convert.ToInt32(row(0)) < 0 Then
        System.Windows.Forms.MessageBox.Show("Invalid Data in Row: " + rowIndex + " - 1st Column is Less Than Zero", "Data Import")
        dataSuccess = False
        Exit For
    End If

    rowIndex = rowIndex + 1
Next

' If Its Good, Bind It
If dataSuccess Then

    DataGridView1.DataSource = dts
    DataGridView1.DataMember = "[Feuil1$]"

End If