【问题标题】:Create table from Excel file从 Excel 文件创建表格
【发布时间】:2018-03-27 07:21:50
【问题描述】:

我正在尝试根据用户上传的 Excel 文件在我的数据库中创建一个临时表。我不明白问题出在哪里以及为什么 Visual Studio 会抛出该异常。

代码

  Private Sub Excel_Load(ByVal filePath As String)
    Dim myConn As SqlConnection
    Dim myCmd As SqlCommand
    Dim sqlCmd As String

    Dim filename As String = Path.GetFileNameWithoutExtension(filePath)

    'Setting up Connection'
    myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;")
    myConn.Open()

    'Create table'
    sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])"

    'Execute Query'
    myCmd = myConn.CreateCommand()
    myCmd.CommandText = sqlCmd
    myCmd.ExecuteNonQuery()
    myConn.Close()
End Sub

例外

SqlException:对象名称“EXCELLINK”无效。

Peu_UNRAE 是我的 Excel 文件。

【问题讨论】:

  • 内部查询将评估为 Select * From Excellink [myfile.xlsx$] 我不确定 VBA,但它看起来确实很奇怪。
  • 在 support.ms 上找到它
  • Visual Studio 与此有什么关系?这些可能会帮助support.microsoft.com/en-us/help/306397/…support.microsoft.com/en-gb/help/321686/…
  • 配置工作簿后,Excellink 后面的三 (3) 个句点很重要 >> "FROM EXCELLINK...[myfile.xlsx$]"
  • @donPablo 最后我想出了如何做到这一点

标签: sql excel vb.net


【解决方案1】:

最后我想出了这个解决方案:

  Dim MyConnection As System.Data.OleDb.OleDbConnection
  Dim fileExcelType As String

  //Get the file extension in order to use the propper provider
  If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
     fileExcelType = "Excel 8.0"
     MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
  Else
     fileExcelType = "Excel 12.0"
     MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
  End If

  //Opening excel connection
  MyConnection.Open()

  Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
  Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
  MyCommand.TableMappings.Add("Table", "    ")
  MyCommand.Fill(dt)

  //Closing connection
  MyConnection.Close()

备注:

我将// 用于 cmets,因为标准 ' 在 StackOverflow 上出现了一些问题

【讨论】:

  • @PatrickHonorez 现在对于 SO,它们是一个字符串,我不知道为什么它在这篇文章中做了这么奇怪的事情,因为我总是在链接开头只使用一个 '评论,它总是有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 2021-08-04
  • 2012-10-16
  • 1970-01-01
  • 2016-06-23
  • 2013-06-12
相关资源
最近更新 更多