excel导入导出
Private Sub Command1_Click()
Dim strconn As String
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
CommonDialog1.Filter = ".xls|*.xls"
CommonDialog1.DialogTitle = "请选择要导入的文件"
CommonDialog1.ShowOpen
strtemp = "[odbc;driver={SQL server};server=127.0.0.1;database=AIS20170828184882;uid=sa;pwd=123456]"
'strconn = "provider=microsoft.ace.oledb.4.0;data source=" & CommonDialog1.FileName & ";extended properties=excel 8.0"
If UCase(Right(ExcelFileAddress, 4)) = UCase(".xls") Then
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CommonDialog1.FileName & ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';Persist Security Info=False"
Else
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CommonDialog1.FileName & ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';Persist Security Info=False"
End If
cn.Open strconn
strsql = "insert into" & strtemp & ".aa select * from [sheet1$]"
cn.Execute strsql
MsgBox "ddd", vbExclamation + vbOKOnly
cn.Close
Set cn = Nothing
End Sub
/************/
Private Sub Command2_Click()
Dim conn As String
Dim rs As New ADODB.Recordset
Dim Excel As Object
Dim workbook As Object
Dim sheet As Object
Dim i&, j&
'SQL数据库的连接字串
conn = "Provider=SQLOLEDB.1;Data source=127.0.0.1;initial catalog=AIS20170828184882;User Id=sa;Password=123456"
'打开到sql的连接,读取xxx表数据到rs
rs.Open "select '学号','名称','课程'", conn, adOpenKeyset, adLockReadOnly
'excel对象、工作簿、工作表
Set Excel = CreateObject("Excel.Application")
Set workbook = Excel.Workbooks().Add()
Set sheet = workbook.sheets(1)
sheet.Name = "课程"
Excel.Visible = True
'循环读取rs并写入到excel
For i = 1 To rs.Fields.Count
j = 1
rs.MoveFirst
Do While Not rs.EOF
j = j + 1
sheet.Cells(j, i) = rs.Fields(i - 1).Value
rs.MoveNext
Loop
Next
rs.Close
Set rs = Nothing
End Sub
这两段代码怎么合并啊,excel数据导入数据库表中,先导出一个空的excel,在里面插入数据,再把这个excel导入到数据库表中