我有一个访问数据库,其中包含一个需要整数的字段。我传递了一些从Excel电子表格中检索到的数据,如果从单元格中检索到字符串,则调用函数的Try / Catch将触发FormatException。我想弄清楚的是,是否可能(并且始终是)抛出一个自定义错误消息,该消息将显示包含无效数据的单元格地址。这是我的一些示例代码。
Public Class Main
Private cellAddress As String
Private Sub btn_Import(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
openFileDialog.Filter = "Excel Files (*.xls)|*.xlsx|All files (*.*)|*.*"
openFileDialog.RestoreDirectory = True
If openFileDialog.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Return
End If
Try
ImportWorksheet(New FileInfo(openFileDialog.FileName))
Catch ex As FormatException
MessageBox.Show("The data contained within cell " & cellAddress & " is invalid.", "Error")
End Try
End Sub
Private Sub ImportWorksheet(ByVal excelFile As FileInfo)
Dim cnn As New OleDbConnection(My.Settings.cnn)
Dim cmd As OleDbCommand = GetCommand("UpdateSite")
Dim worksheet1 As ExcelWorksheet = package.Workbook.Worksheets(1)
Using package As New ExcelPackage(excelFile)
Using cmd.Connection
cmd.Connection.Open()
cmd.Parameters.Add("@MyData", OleDbType.Integer).Value = GetCellContents(worksheet1, "K8")
cmd.ExecuteNonQuery()
End Using
End Sub
Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String) As Object
If worksheet.Cells(address).Value Is Nothing Then
Return DBNull.Value
Else
cellAddress = address
Return worksheet.Cells(address).Value
End If
End Function
End Class
不要以为我在这里遗漏任何东西,我有点复制和粘贴并修改代码以缩短并且不放弃任何不需要的信息。一旦代码命中ExecuteNonQuery()方法,错误就会冒泡并说出我写的任何内容。如果发生这种情况,我想传递单元格地址,以便他们知道在哪里查看。
我能想到这样做的唯一方法是添加一个类级变量,并在每次获取值时将其设置为当前单元格。唯一的问题是,因为它只在ExecuteNonQuery()触发,并且我有多个参数,如果第一个添加的参数无效但下一个参数不是,那么每次都将单元格设置为最后一个参数,我得到了错误的结果。有没有办法从数据库中获取某种消息,告诉我具体哪个参数没有正确转换?
答案 0 :(得分:0)
没关系,我现在就跟它一起去了......这很有效,但如果你们能给我一些更好的东西,请做。
cmd.Parameters.Add("@MyData", OleDbType.Integer).Value = GetCellContents(worksheet2, "K8", "Int32")
Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String, Optional ByVal type As String = Nothing) As Object
If worksheet.Cells(address).Value Is Nothing Then
Return DBNull.Value
Else
cellAddress = address
Select Case type
Case Is = "String"
Return Convert.ToString(worksheet.Cells(address).Value)
Case Is = "Int32"
Return Convert.ToInt32(worksheet.Cells(address).Value)
Case Is = "DateTime"
Return Convert.ToDateTime(worksheet.Cells(address).Value)
Case Else
Return worksheet.Cells(address).Value
End Select
End If
End Function