。从excel文件中读取数据时更改为#

时间:2010-10-10 23:38:20

标签: .net database excel-2007

我使用以下代码将excel数据读入数据表,但是数据表中的列名P.O.BOX已更改为P#O#BOX。任何人都可以了解为什么会发生这种情况?

Dim FileName As String = "C:\abc.xls"
    Dim conn As Data.OleDb.OleDbConnection = Nothing
    Dim dt As New DataTable

    Try
        Try
            Try
                conn = New Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", FileName))
                conn.Open()
            Catch exOleDB As System.Data.OleDb.OleDbException
                If exOleDB.ErrorCode <> -2147467259 Then Throw exOleDB
                'try to open an Excel 2007 file
                conn = New Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", FileName))
                conn.Open()
            End Try
        Catch ex As Exception
            Throw New Exception("Can't read the import file. Try saving the file as an Excel 97-2003 Workbook (.xls). Also check the file permissions and impersonation settings.", ex)
        End Try
        Using selectedCMD As New Data.OleDb.OleDbCommand("select * from [Users$]", conn)
            Using da As New Data.OleDb.OleDbDataAdapter
                da.SelectCommand = selectedCMD
                da.Fill(dt)
            End Using
        End Using
    Finally
        If conn IsNot Nothing Then
            If conn.State <> ConnectionState.Closed Then conn.Close()
            conn.Dispose()
        End If
    End Try
    Return dt

2 个答案:

答案 0 :(得分:1)

句号“。”在P.O.Box中,它们不是有效的SQL列名,因此数据适配器使它们符合规范。你必须查找原因和内容

答案 1 :(得分:0)

您需要手动处理数据集的填充而不是使用fill()。您可以使用OpenSchema获取Excel中工作表和列的名称,以构造一个限定所有对象名称的SQL语句。

更多详情here