大家好,我在构建项目时遇到问题 我尝试使用批量复制将excel文件导入sql server 2016,我收到了此错误
"' DAFTAR1 $'不是有效的名称。确保它不包含无效字符或标点符号,并且它不会太长"
我认为此代码存在问题 Dim query_excel As String =" SELECT * from [" &安培;档案& " $]"
我在另一台电脑上尝试了所有这些代码并且它运行良好但在我的电脑上却出现了错误,我不知道我错了什么,我使用的是visual basic 2010专业版,sql管理服务器2016和微软Office 2016
任何人都可以帮我弄清楚代码有什么问题吗?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
file = System.IO.Path.GetFileNameWithoutExtension(TextBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim koneksi_excel As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;Data Source='" & TextBox1.Text & "';Extended Properties=""Excel 12.0 Xml;HDR=YES;""")
koneksi_excel.Open()
Dim query_excel As String = "SELECT * from [" & file & "$]"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(query_excel, koneksi_excel)
Dim rd As OleDb.OleDbDataReader
rd = cmd.ExecuteReader()
Dim koneksi As New SqlClient.SqlConnection()
Dim koneksidatabase As String = "server=DESKTOP-KJQ8PNO\SQLEXPRESS;database=otto;Integrated Security=True"
koneksi.ConnectionString = koneksidatabase
koneksi.Open()
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet()
Dim dt As New DataTable
ds.Tables.Add(dt)
da = New OleDb.OleDbDataAdapter(query_excel, koneksi_excel)
da.Fill(dt)
Using bulkcopy As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(koneksi)
bulkcopy.DestinationTableName = file
bulkcopy.BulkCopyTimeout = 600
bulkcopy.WriteToServer(rd)
rd.Close()
MsgBox("Data uploaded to database", MsgBoxStyle.Information, "Uploaded")
TextBox1.Text = ""
End Using
End Sub
答案 0 :(得分:0)
如果 您正在使用DataGridView
或其他网格来查看数据,这是您查看数据并加载数据的一种方法进入网格。
Using ofd As New OpenFileDialog
ofd.InitialDirectory = dir
ofd.Filter = "Excel Files (*.xlsx)|*.xlsx| XLS Files (*.xls)|*.xls"
ofd.FilterIndex = 1
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
txtFile.Text = ofd.FileName
fi = New FileInfo(ofd.FileName)
fileName = ofd.FileName
excel = fi.FullName
eCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
excel & ";Extended Properties='Excel 12.0;IMEX=1;';")
eCon.Open()
Dim dtSheets As DataTable = eCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
If drSheet.Item("TABLE_NAME").ToString() <> "Sheet1$" Then
listSheet.Add(drSheet("TABLE_NAME").ToString())
Else
End If
Next
Me.Cursor = Cursors.WaitCursor
Dim myTable = ""
myTable = listSheet.Item(0)
da = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTable), eCon)
ds = New DataSet
da.Fill(ds, myTable)
Dim dt As DataTable = ds.Tables(0).Copy()
在此处,将dt
设置为网格DataSource
。这样你就知道你总是得到第一张工作表,而不必担心这个名字是什么,程序就是为你准备的。
玩一个让我知道的游戏。或者,您可以使用此代码获取Excel工作表并使用已有的导入。