导入电子表格但遇到问题

时间:2010-04-09 19:31:28

标签: asp.net vb.net excel

我有一个允许用户导入电子表格的表单。当涉及列标题时,此电子表格通常是静态的,但现在用户希望能够包含可选列(称为Notes)。当我尝试从电子表格中读取列时,我的代码崩溃了。

        Dim objCommand As New OleDbCommand()
        objCommand = ExcelConnection() 'function that opens spreadsheet and returns objCommand

        Dim reader As OleDbDataReader
        reader = objCommand.ExecuteReader()

        While reader.Read()
            Dim Employee As String = Convert.ToString(reader("User"))
            Dim SerialNUM As String = Convert.ToString(reader("serialno"))
            **Dim Notes As String = Convert.ToString(reader("notes"))**

如果电子表格包含Notes列,则一切顺利。如果没有,崩溃。如何查看电子表格中是否存在Notes列以避免崩溃?

2 个答案:

答案 0 :(得分:1)

也许OleDbDataReader.FieldCount可以帮助您编写解决方法。

答案 1 :(得分:1)

将代码更改为以下内容: [编辑 - 更改了代码逻辑]

Dim fieldCount = reader.FieldCount 
For i = 0 To fieldCount - 1
Dim colName = reader.GetName(i)
If (colName = "notes") Then
    Dim Notes As String = reader.GetString(i)
End If
Next i